I am handling REST exceptions using @ControllerAdvice
and ResponseEntityExceptionHandler
in a spring Rest webservice. So far everything was working fine until I decided to add the URI
path(for which exception has occurred) into the BAD_REQUEST response.
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
logger.info(request.toString());
return handleExceptionInternal(ex, errorMessage(HttpStatus.BAD_REQUEST, ex, request), headers, HttpStatus.BAD_REQUEST, request);
}
private ApiError errorMessage(HttpStatus httpStatus, Exception ex, WebRequest request) {
final String message = ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage();
final String developerMessage = ex.getCause() == null ? ex.toString() : ex.getCause().getMessage();
return new ApiError(httpStatus.value(), message, developerMessage, System.currentTimeMillis(), request.getDescription(false));
}
ApiError is just a Pojo class:
public class ApiError {
private Long timeStamp;
private int status;
private String message;
private String developerMessage;
private String path;
}
But WebRequest has not given any api to get the path for which the request failed. I tried:
request.toString()
returns -> ServletWebRequest: uri=/signup;client=0:0:0:0:0:0:0:1
request.getDescription(false)
returns -> uri=/signup
getDescription
is pretty close to the requirement, but doesn't meet it. Is there any way to get only the uri part?
Found the solution. Casting WebRequest
to ServletWebRequest
solved the purpose.
((ServletWebRequest)request).getRequest().getRequestURI().toString()
returns the complete path - http://localhost:8080/signup