@ExceptionHandler处理异常

@ExceptionHandler() 如果异常被try-catch就不会被接收, 抛出的checked exception 能被接收

@RestController
public class TestController2 {
    @RequestMapping("/test5")
    public String test5() {
        try {
            throw new RuntimeException();
        } catch (RuntimeException e) {
            System.out.println("异常被捕获");
            e.printStackTrace();
        }
        return "hello world";
    }

    @RequestMapping("/test6")
    public void test6() throws IOException {
        System.out.println("controller IOException throws");
        throw new IOException();
    }

    @RequestMapping("/test7")
    public void test7()  {
        try {
            throw new IOException();
        } catch (IOException e) {
            System.out.println("controller IOException try-catch");
            e.printStackTrace();
        }
    }
    /*
    @ExceptionHandler 能接收抛出的checked exception,但是如果异常被try-catch就不能被接收
     */
    @ExceptionHandler(IOException.class)
    public void catchIoException() {
        System.out.println("handler  IOException");
    }
    /*
    如果unchecked exception 被try-catch了就不能被@ExceptionHandler接收
     */
    @ExceptionHandler(RuntimeException.class)
    public void catchRuntimeException() {
        System.out.println("handler  RuntimeException");
    }
}

可以通过如下方法处理异常

    @ExceptionHandler(AuthorizationException.class)
    private ModelAndView handleAuthorizationException(AuthorizationException e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "你没有权限这么做");
        //如果要自定义传属性到getAttributes()中必须通过这种方法,不能通过@RequestStatus
        map.put("javax.servlet.error.status_code", HttpStatus.BAD_REQUEST.value());
        return new ModelAndView("forward:/error", map);
    }
原文地址:https://www.cnblogs.com/kikochz/p/12821758.html