springboot2.0---06、自定義異常404頁面跳轉,500json處理
阿新 • • 發佈:2018-12-20
1.定義異常控制器
@Controller @ControllerAdvice @RequestMapping("/error") public class ErrorController { private static final Logger logger = LoggerFactory.getLogger(ErrorController.class); public static final String DEFAULT_ERROR_VIEW = "error"; /************** 404異常處理 ***********/ @GetMapping("/404") public void error404(HttpServletResponse response){ try { response.sendRedirect("/error/demo"); } catch (IOException e) { e.printStackTrace(); } } @GetMapping("/page") public String error404(){ return "/error/404"; } /************** 500異常處理 ***********/ @GetMapping("/500") @ExceptionHandler(value = Exception.class) @ResponseBody public Object error500(HttpServletRequest request, HttpServletResponse response, Exception e) { logger.debug(getClass().getName() + ".errorHandler】統一異常處理:request="+request); return ResultUtil.fail(500,e.getMessage()); } }
2.自定義異常
public class AdminException extends RuntimeException { private Integer code; private String message; public AdminException(Integer code, String message) { super(message); this.code = code; this.message = message; } public AdminException(ExceptionEnum exceptionEnum) { super(exceptionEnum.getMsg()); this.code = exceptionEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }