Spring全局异常捕获
package org.xxx.ac.zpk.exception; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import org.wpwl.ac.utils.JSONUtils; import org.wpwl.ac.zpk.entity.ApiResult; /** * 异常处理 * @author xxx * */ public class ExceptionHandler implements HandlerExceptionResolver { private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); /* 使用response返回 */ response.setStatus(HttpStatus.OK.value()); // 设置状态码 response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType response.setCharacterEncoding("UTF-8"); // 避免乱码 response.setHeader("Cache-Control", "no-cache, must-revalidate"); try { ApiResult json = getExceptionResult(ex); response.getWriter().write(JSONUtils.bean2Json(json)); } catch (IOException e) { logger.error("与客户端通讯异常:" + e.getMessage(), e); } logger.debug("异常:" + ex.getMessage(), ex); return mv; } private ApiResult getExceptionResult(Exception ex) { ApiResult result; if (ex instanceof WPException) { result = ApiResult.err(ex.getMessage()); } else { result = ApiResult.err("服务异常!"); } return result; } }
<bean id="exceptionResolver" class="org.wpwl.ac.zpk.exception.ExceptionHandler"/>
package org.wpwl.ac.zpk.exception; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.wpwl.ac.zpk.entity.ApiResult; public class ExceptionController { // private static final Logger logger = LoggerFactory.getLogger(BaseController.class); @ExceptionHandler @ResponseBody public ApiResult exception(HttpServletRequest request, Exception e) { //添加自己的异常处理逻辑,如日志记录 request.setAttribute("exceptionMessage", e.getMessage()); // e.printStackTrace(); // logger.error(e.getMessage()); // 根据不同的异常类型进行不同处理 if(e instanceof WPException){ return ApiResult.err(e.getMessage()); } else{ return ApiResult.err("服务异常!"); } } }