1. ExceptionHandler仅仅处理当前controller的Exception
@RestController @RequestMapping("/ex") public class ExController { @GetMapping("thex") public String throwEx() throws Exception { throw new Exception("exception thrown from ExController.throwEx"); } @GetMapping("fnfex") public String FileNotFound() throws Exception { throw new FileNotFoundException("FileNotFoundException thrown from ExController.throwEx"); } @ExceptionHandler(FileNotFoundException.class) public String exHandler(Exception e) { System.out .println("==================ExController.exHandler==================================================="); e.printStackTrace(); return e.getMessage() + " from ExController.exHandler"; } } |
2.@ControllerAdvice
用以定义全局异常处理,当controller自己的@
ExceptionHandler无法处理时,就交给全局的@ControllerAdvice 中定义的@
ExceptionHandler,
@ExceptionHandler
methods in @ControllerAdvice
can be used to handle exceptions from any @Controller
or any other handler.
@ControllerAdvice(annotations = { Controller.class, RestController.class }) public class AdController { @ResponseBody @ExceptionHandler(Exception.class) public Map errorHandler(Exception ex) { Map errorMap = new HashMap(); errorMap.put("msg", ex.getMessage()+" from AdController"); System.out.println("---------------in AdController.errorHandler "); return errorMap; } @ExceptionHandler(IOException.class) public Map errorHandler2(IOException ex,, HttpServletRequest request) { .....} @ExceptionHandler(FileNotFoundException.class) public Map errorHandler3(FileNotFoundException ex) { .....} } 3.BasicErrorController BasicErrorController用来处理前两个处理不了的Exception
----------------------------------------------------------------------------------------------------------------------------------------------- @ControllerAdvice("org.example.controllers") |