0

How to throw a 404 code with a message "Could not find object with id " + id?

@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);
    }
}

This one results in an empty message.

    "status": 404,
    "error": "Not Found",
    "message": "",
Vpmk5
  • 1
  • 1
  • 1
    Does this answer your question? [Add a body to a 404 Not Found Exception](https://stackoverflow.com/questions/36848562/add-a-body-to-a-404-not-found-exception) – Faramarz Afzali Sep 08 '21 at 13:52

2 Answers2

0

Try something like this maybe:

@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 "";
    }
}
0

You can achieve this with @ControllerAdvice and @ExceptionHandler as follows:

Create a custom base exception for your project:

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

Update your exception as follows:

@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);
    }
}

Create an object to use as an answer:

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

Create the Global Exception handler to your project:

@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;
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45