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);
        }
    
  • 相关阅读:
    css的三种特性
    css选择器
    margin:0 auto 与 text-align:center 的区别
    JS如何实现点击页面内任意的链接均加参数跳转
    css和js带参数(形如.css?v=与.js?v= 或 .css?version=与.js?version=)
    移动端页面前端设计随笔整理
    理解:Before和:After伪元素
    时下流行的css3页面纵向滑动效果
    webapp网页调试工具Chrome Devtools
    做手机web半年遇到的问题及解决方法
  • 原文地址:https://www.cnblogs.com/kikochz/p/12821758.html
Copyright © 2011-2022 走看看