zoukankan      html  css  js  c++  java
  • @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);
        }
    
  • 相关阅读:
    逆序对的相关问题:bzoj1831,bzoj2431
    bzoj3211,bzoj3038
    hdu 1179最大匹配
    hdu 3038带权并查集
    poj 1733离散化(map)+并查集
    codeforces 369B
    poj 1456
    POJ 1988相对偏移
    poj 1986tarjan模板题
    poj 1330lca模板题离线算法
  • 原文地址:https://www.cnblogs.com/kikochz/p/12821758.html
Copyright © 2011-2022 走看看