更新时间:2021-09-15 23:38:27
您可以使用 @ControllerAdivce
注释创建一个附加类,然后再添加一个您将能够为每个异常编写自定义响应逻辑,例如:
You can create an additional class with @ControllerAdivce
annotation and later you will be able to write custom response logic for each exception e.g:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({SQLException.class})
public ResponseEntity<Object> sqlError(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Some SQL exception occured");
}
}
此外,您可以扩展 ResponseEntityExceptionHandler ,并覆盖从异常到HTTP响应的映射的默认行为。
Also, you can extend ResponseEntityExceptionHandler and override the default behavior for mapping from exceptions to HTTP response.
另外,请查看此,它可为您的案件提供非常有用的信息。
Also, take a look at this, it holds very usefull information for your case.