向404异常添加消息



如何抛出带有消息"Could not find object with id " + id的404代码?

@ResponseStatus(code = HttpStatus.NOT_FOUND, 
reason = "Could not find object with id")
public class ObjectNotFoundException extends RuntimeException {
ObjectNotFoundException(long id) {
super("Could not find object with id " + id);
}
}

这将导致一个空消息。

"status": 404,
"error": "Not Found",
"message": "",

试试这样做:

@ResponseStatus(code = HttpStatus.NOT_FOUND, 
reason = "Could not find recipe with id")
public class RecipeNotFoundException extends RuntimeException {
RecipeNotFoundException(long id) {
super("Could not find recipe with id " + id);
}
public String getMessage() {
return super.getMessage(); // not "";
}
}

您可以使用@ControllerAdvice@ExceptionHandler实现此目的,如下所示:

为您的项目创建一个自定义基异常:

public abstract class CustomException extends RuntimeException {
public LunchRouletteException(Throwable cause, String message, Object... arguments) {
super(MessageFormat.format(message, arguments), cause);
}
}

更新你的异常如下:

@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class ObjectNotFoundException extends CustomException {
private static final String ERROR_MESSAGE = "Could not find object with id";
public ObjectNotFoundException(Throwable cause) {
super(cause, ERROR_MESSAGE);
}
}

创建一个对象作为答案:

public class ErrorInfo {
private final int errorCode;
private final String errorMessage;
}

为您的项目创建全局异常处理程序:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {CustomException.class})
public ResponseEntity<Object> handleCustomExceptions(Exception exception, WebRequest webRequest) {
HttpStatus errorCode = this.resolveAnnotatedResponseStatus(exception);
return this.handleExceptionInternal(exception, 
new ErrorInfo(errorCode.value(), exception.getMessage()), new HttpHeaders(), errorCode, webRequest);
}
private HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
return Objects.nonNull(annotation) ? annotation.value() : HttpStatus.INTERNAL_SERVER_ERROR;
}
}