我正在尝试实现自定义HttpStatus代码系统,以便为我的REST服务提供错误信息。
为此,我实施了一个新的Enum,CustomHttpStatus
public enum CustomHttpStatus {
ERROR1(42, "Error 1"),
ERROR2(43, "Error 2"),
ERROR3(44, "Error 3"),
ERROR4(45, "Error 4"),
ERROR5(46, "Error5");
private CustomHttpStatus(int value, String reason) {
this.value = value;
this.reason = reason;
}
private final int value;
private final String reason;
public int getValue() {
return value;
}
public String getReason() {
return reason;
}
}
然后,我有一个类,其中包含有关错误的信息并管理标准HTTPStatus和我的CustomHttpStatus
public class ApiError {
private HttpStatus status;
private CustomHttpStatus customStatus;
private String message;
private List<String> errors;
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public ApiError(HttpStatus status, String message, List<String> errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public ApiError(HttpStatus status, String message, String error) {
super();
this.status = status;
this.message = message;
errors = Arrays.asList(error);
}
public ApiError(CustomHttpStatus customStatus, String message, List<String> errors) {
super();
this.customStatus = customStatus;
this.message = message;
this.errors = errors;
}
public ApiError(CustomHttpStatus customStatus, String message, String error) {
super();
this.customStatus = customStatus;
this.message = message;
errors = Arrays.asList(error);
}
public CustomHttpStatus getCustomStatus() {
return customStatus;
}
public void setCustomStatus(CustomHttpStatus customStatus) {
this.customStatus = customStatus;
}
}
接下来,在@ControllerAdvice
类中,我定义了如何响应错误,例如
@ExceptionHandler(PlateNumberExistsExceptionAPI.class )
protected ResponseEntity<Object> handlePlateNumberExistExceptionAPI(PlateNumberExistsExceptionAPI ex, WebRequest request) {
StringBuilder builder = new StringBuilder();
builder.append(ex.getMessage());
ApiError apiError = new ApiError(CustomHttpStatus.ERROR1,
ex.getLocalizedMessage(), builder.substring(0, builder.length()));
logger.debug("ApiError is " + apiError.toString());
logger.error("Plate exists - API", ex);
return ResponseEntity.status(apiError.getCustomStatus().getValue())
.headers(new HttpHeaders())
.contentType(MediaType.APPLICATION_JSON).body(apiError);
}
问题是我需要为ResponseEntity使用BodyBuilder
,构造函数需要HttpStatus
值。应用程序响应我的自定义错误,但没有消息,它需要60000毫秒来回答...
我不知道为什么需要这么长时间,很快就会遇到异常并且ApiError会产生,问题出在响应上