java在SpringBoot 2.0.4的RestController中捕获算术异常。释放
我有一个基本的SpringBoot 2.0.4。发布应用程序。使用Spring初始值设定项、JPA、嵌入式Tomcat、Thymeleaf模板引擎,并将包作为可执行的JAR文件
我创建了这个类来管理异常:
@ControllerAdvice
@RestControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public RestResponseEntityExceptionHandler() {
super();
}
// 500
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class, RuntimeException.class })
/*500*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public BodyBuilder handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
该方法处理RuntimeException和算术异常 扩展RuntimeException
为了测试它,我创建了这个方法
GetMapping(path = "/getUsers", consumes = "application/json", produces = "application/json")
public ResponseEntity<List<User>> testErrors(HttpServletRequest request) {
double ss = 3 /0;
return ResponseEntity.ok(userService.findAll());
}
期望它只返回一个HttpStatus.INTERNAL_SERVER_ERROR
,但它会返回“
{"timestamp":"2018-08-31T09:21:21.717+0000","status":500,"error":"Internal Server Error","message":"/ by zero","trace":"java.lang.ArithmeticException: / by zero\n\tat ...
用这种方法
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class, RuntimeException.class })
/*500*/
public BodyBuilder handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
}
我有完整的追踪:{"timestamp":"2018-09-03T07:04:58.803+0000","status":500,"error":"Internal Server Error","message":"/ by zero","trace":"java.lang.ArithmeticException: / by zero\n\tat
对于这一个,我在控制台中没有看到任何卷曲:
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class, RuntimeException.class })
/*500*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public void handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
}
而另一个,也没有在控制台中:
@ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class, RuntimeException.class })
/*500*/
public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
logger.error("500 Status Code", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
共 (0) 个答案