要在REST中移除HTTP错误的“message”详情,可以通过自定义异常处理器来实现。以下是一个使用Spring Boot的示例:
ApiException.java
:public class ApiException extends RuntimeException {
private HttpStatus status;
private String message;
public ApiException(HttpStatus status, String message) {
this.status = status;
this.message = message;
}
public HttpStatus getStatus() {
return status;
}
public String getMessage() {
return message;
}
}
GlobalExceptionHandler.java
:@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class)
public ResponseEntity handleApiException(ApiException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getStatus(), ex.getMessage());
return new ResponseEntity<>(errorResponse, ex.getStatus());
}
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "An error occurred");
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
ErrorResponse.java
:public class ErrorResponse {
private HttpStatus status;
private String message;
public ErrorResponse(HttpStatus status, String message) {
this.status = status;
this.message = message;
}
public HttpStatus getStatus() {
return status;
}
public String getMessage() {
return message;
}
}
@RestController
public class MyController {
@GetMapping("/api/some-endpoint")
public ResponseEntity someEndpoint() {
// 模拟出现错误
throw new ApiException(HttpStatus.BAD_REQUEST, "请求参数错误");
}
}
这样,在发生异常时,错误信息将以JSON格式返回给客户端。例如,如果请求/api/some-endpoint
时发生错误,响应将类似于以下内容:
{
"status": "BAD_REQUEST",
"message": "请求参数错误"
}
通过自定义异常处理器,我们可以更好地控制HTTP错误的“message”详情,并将其以友好的方式返回给客户端。