@ControllerAdvice public class DefaultExceptionHandler {
@ExceptionHandler({UnauthorizedException.class}) @ResponseStatus(HttpStatus.UNAUTHORIZED) public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("/Error/Unauthorized"); return mv; }
@ExceptionHandler({RuntimeException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView processRuntimeException(NativeWebRequest request, RuntimeException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("/Error/Error"); return mv; }
@ExceptionHandler({MessageException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView processMessageException(NativeWebRequest request, MessageException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("/Error/NotFound"); return mv; }
@ExceptionHandler({DuplicateKeyException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView processDuplicateKeyException(NativeWebRequest request, DuplicateKeyException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("/Error/500"); return mv; }
@ExceptionHandler({Exception.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ModelAndView processException(NativeWebRequest request, Exception e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e); mv.setViewName("/Error/404"); return mv; }
} 捕獲異常也可以返回json: @ExceptionHandler @ResponseBody public APIManageBaseResp exceptionHandler(Exception e) { logger.error("調(diào)用接口出現(xiàn)異常:{}",e); APIManageBaseResp<String> resp = new APIManageBaseResp(); resp.setResultCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); if(e instanceof MessageException){ resp.setErrorMsg(e.getMessage()); }else{ resp.setErrorMsg("調(diào)用接口出現(xiàn)異常:"+e.getMessage()); } resp.setDataFiled(""); return resp; }
@RequestMapping(value = "/testFacade") @ResponseBody public String testFacade() { int a = 1/0;
return "ok"; }
@RequestMapping(value = "/testFacade1") @ResponseBody public String testFacade1() throws MessageException { throw new MessageException("錯(cuò)了en ");
}
@RequestMapping(value = "/testFacade2") @ResponseBody public String testFacade2() { throw new UnauthorizedException("錯(cuò)了b ");
}
@RequestMapping(value = "/testFacade3") @ResponseBody public String testFacade3() { throw new RuntimeException("錯(cuò)了a ");
}
|