Springboot配置全局异常处理类

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"
}

猜你喜欢

转载自blog.csdn.net/jiasunan/article/details/82078392