0%
方式1:实现HandlerExceptionResolver接口
不推荐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public class HandlerExceptionResolverImpl implements HandlerExceptionResolver {
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Logger logger = LoggerUtil.getLogger(ex.getClass()); logger.info(ex.getMessage());
response.setStatus(404); response.setContentType("application/json; charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache, must-revalidate"); try { ObjectMapper objectMapper = new ObjectMapper(); String s = objectMapper.writeValueAsString(ResponseMsg.fail.setMsg("未知错误,请联系管理员!")); response.getWriter().write(s); } catch (IOException e) { logger.error("与客户端通讯异常:"+ e.getMessage(), e); } return null; } }
|
方式二:使用注解方式
1 2 3 4 5 6 7 8 9 10
|
@ControllerAdvice public class HandlerExectionResponse { @ExceptionHandler(value = HandlerException.class) @ResponseBody public ResponseMsg jsonExceptionHandler(HttpServletRequest request, HandlerException e) { return ResponseMsg.fail.setMsg(e.getMessage()); } }
|