How to throw an error message when there is no method mapping in Spring controller

53 views Asked by At

How to throw an error message when there is no method mapping in Spring controller. In the following example GET /api/v1/foos doesn't exist, is there a way to throw a generic message (say api/v1/foos doesn't exist) instead of the default message.

{{base_url}}/fa/api/v1/foos/
{
    "message": "No static resource api/v1/foos.",
    "status": 500,
    "timestamp": "2024-02-29T12:58:50.813294104"
}
1

There are 1 answers

0
PhantomPhreak1995 On

You could define global elements in an ExceptionController or whatever you want to call it:

@ControllerAdvice 
public class GlobalExceptionHandler 
{

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        return new ResponseEntity<>("The requested method does not exist.", HttpStatus.NOT_FOUND);
    }
        @ExceptionHandler(NoSuchMethodException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleNoSuchMethodException(NoSuchMethodException ex) {
        return new ResponseEntity<>("The requested method does not exist.", HttpStatus.NOT_FOUND);
    }

}

You can use custom classes, send parameters into those or simply use strings (as a parameter) for the message you want to send through these default exception classes.