springboot的全局异常处理
1. 新建一个类GlobalDefaultExceptionHandler 在class上注解 @ControllerAdvice 方法上注解 @ExceptionHandler(value=Exception.class)
这样程序出错, 就会返回默认配置的信息了
package com.iwhere.scrapy.exception; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import com.iwhere.scrapy.enums.PublicRespEnum; import com.iwhere.scrapy.model.ResponseModel; @ControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(Exception.class) @ResponseBody public ResponseModel defaultHandler(HttpServletRequest request, Exception exception) { StringBuffer url = request.getRequestURL(); String params = request.getQueryString(); // 发生地点 int lineNum = 0; String className = null; String methodName = null; StackTraceElement[] st = exception.getStackTrace(); if (ArrayUtils.isNotEmpty(st)) { lineNum = st[0].getLineNumber(); className = st[0].getClassName(); methodName = st[0].getMethodName(); } String message = exception.getMessage(); LOGGER.info("Exception: {}#{}() 在第{}行发生{}异常!!! url: {}, params: {}, info: {}", className, methodName, lineNum, exception.getClass().getName(), url, params, message); return ResponseModel.getModel(PublicRespEnum.RESCODE_500, message); } }
其中ResponseModel 是一个统一返回模型
原创地址: http://www.cnblogs.com/wenbronk/p/6850785.html 转载请注明出处, 谢谢