3 回答
TA贡献1785条经验 获得超4个赞
如果您希望对 API 进行全局异常处理,并且更喜欢自定义错误响应,您可以添加@ControllerAdvice:
@ControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler({ ApiException.class })
protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException ex) {
return new ResponseEntity<>(new ApiErrorResponse(ex.getStatus(), ex.getMessage(), Instant.now()), ex.getStatus());
}
}
// you can put any information you want in ApiErrorResponse
public class ApiErrorResponse {
private final HttpStatus status;
private final String message;
private final Instant timestamp;
public ApiError(HttpStatus status, String message, Instant timestamp) {
this.status= status;
this.message = message;
this.timestamp = timestamp;
}
public HttpStatus getStatus() {
return this.status;
}
public String getMessage() {
return this.message;
}
public Instant getTimestamp() {
return this.timestamp;
}
}
// your custom ApiException class
public class ApiException extends RuntimeException {
private final HttpStatus status;
public ApiException(HttpStatus status, String message) {
super(message);
this.status = status;
}
public HttpStatus getStatus() {
return this.status;
}
}
TA贡献1796条经验 获得超7个赞
如果您需要有限数量的不同错误消息,或者您想多次重复使用相同的错误消息,那么您只需要这样:
@ResponseStatus(value = HttpStatus.CONTINUE, reason = "No have content")
public class AppException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
不需要任何额外的类和处理程序。您的代码将清晰而简单。
您可以像这样简单地提高它:
throw new AppException();
TA贡献1803条经验 获得超6个赞
有多种方法可以实现这一点:
异常处理程序
您可以@ExceptionHandler在控制器中添加带注释的方法:
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public void handleException() {
//
}
处理程序异常解析器
您还可以实现自定义解析器来拦截所有异常并通过覆盖doResolveException方法来全局处理它们
可以在此处找到有关上述两种方法的更多详细信息:https ://www.baeldung.com/exception-handling-for-rest-with-spring
添加回答
举报
