1.創(chuàng)建異常處理類
@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";
}
}
錯(cuò)誤結(jié)果:
{
"detail": {
"methodName": "hello",
"fileName": "HelloController.java",
"lineNumber": 13,
"className": "com.example.app.controller.HelloController",
"nativeMethod": false
},
"message": "/ by zero"
}