美文网首页
SpringBoot 异常处理类

SpringBoot 异常处理类

作者: 消失的码农 | 来源:发表于2019-12-26 14:49 被阅读0次

    1.创建异常处理类

    @ControllerAdvice
    public class GlobalExceptionHandler {
     
        @ExceptionHandler(RuntimeException.class)
        @ResponseBody
        public Map<String, Object> exceptionHandler(Exception e){
            Map<String, Object>  map = new HashMap<String, Object>();
            map.put("message", e.getMessage());
            map.put("detail", e.getStackTrace()[0]);
            return map;
        }
    }
    

    2.测试

    @RestController
    public class HelloController {
        @RequestMapping("/hello")
        public String hello(){
            int i = 1/0;
            return "hello exception";
        }
    }
     
    错误结果:
     
    {
        "detail": {
            "methodName": "hello",
            "fileName": "HelloController.java",
            "lineNumber": 13,
            "className": "com.example.app.controller.HelloController",
            "nativeMethod": false
        },
        "message": "/ by zero"
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot 异常处理类

          本文链接:https://www.haomeiwen.com/subject/yvakoctx.html