Prakash
Prakash

Reputation: 273

How to suppress Spring boot error message

Team,

The Spring boot throws error response 405(Correct response),but due to security reason the error message should be suppressed with out path message.

{
"timestamp": 1554394589310,
"status": 405,
"error": "Method Not Allowed",
"exception": 
"org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/testproject/datasets12/"
}

Help me to solve the issue by returning the response without path message.

Upvotes: 0

Views: 1761

Answers (1)

Misantorp
Misantorp

Reputation: 2831

As pointed out by Shaunak Patel, the way to handle this is a custom error handler. There are plenty of ways to implement one, but a simple implementation getting you the result you want is something like this

@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Map<String, Object> handleConstraintViolationException(HttpRequestMethodNotSupportedException ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", Instant.now().toEpochMilli());
        response.put("status", HttpStatus.METHOD_NOT_ALLOWED.value());
        response.put("error", HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
        response.put("exception", ex.getClass().getName());
        response.put("message", String.format("Request method '%s' not supported", ex.getMethod()));
        return response;
    }
}

A curl command to illustrate

$ curl -v -X POST 'localhost:8080/testproject/datasets12/'
{
  "exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
  "error": "Method Not Allowed",
  "message": "Request method 'POST' not supported",
  "timestamp": 1554400755087,
  "status": 405
}

Upvotes: 3

Related Questions