I want to return HTTPStatus code dynamically like 400, 400, 404 etc as per the response object error. I was referred to this question - Programmatically change http response status using spring 3 restful but it did not help.
I have this Controller class with an @ExceptionHandler
method
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(CustomException e) {
return new ResponseEntity<MyErrorResponse>(
new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
ExceptionUtility.getHttpCode(e.getCode()));
}
ExceptionUtility
is a class where I have the two methods used above (getMessage
and getCode
).
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
}
I do not want to check in if condition and return the response code accordingly, Is there any other better approach to do this?