SpringBoot 异常处理类

2019-12-26  本文已影响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"
}
上一篇下一篇

猜你喜欢

热点阅读