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);
        }
    
  • 相关阅读:
    大数据综合案例--搜狗搜索日志分析
    大数据综合案例-网站日志分析
    Python格式化字符串
    python爬虫---selenium库的用法
    python爬虫---BeautifulSoup的用法
    python爬虫---requests库的用法
    python爬虫---urllib库的基本用法
    Codeforces Round #501 (Div. 3) ABDE1E2
    2018 Multi-University Training Contest 4 B Harvest of Apples 莫队算法
    莫队算法
  • 原文地址:https://www.cnblogs.com/kikochz/p/12821758.html
Copyright © 2011-2022 走看看