I'm working on internationalization on an existing Spring boot project, I've been having issues trying to figure out if default spring/spring boot errors can be converted automatically.
I have it working for MethodArgumentNotValidException
spring somehow converts it to the language specified in the request header
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public ResponseEntity<Object> handleBadRequest(MethodArgumentNotValidException ex, WebRequest request) {
Locale locale = request.getLocale();
ApiResponseEnvelope envelope = new ApiResponseEnvelope(false);
BindingResult result = ex.getBindingResult();
List<FieldError> errors = result.getFieldErrors();
for (FieldError err : errors) {
ApiError ae = new ApiError(messageSource.getMessage(err, locale), 44);
envelope.addError(ae);
}
return new ResponseEntity(envelope, HttpStatus.BAD_REQUEST);
}
Response:
{
"success": false,
"result": null,
"errors": [
{
"message": "ne peut pas être nul",
"code": 44
},
{
"message": "ne peut pas être nul",
"code": 44
},
.
.
.
But now for other exceptions that go through the @ExceptionHandler(Exception.class)
handler it returns the exception as English. I believe somehow Spring should have a way of returning these generic errors in a localized language.
Below the only way I can seem to convert an exception handled by the Exception.class
handler is by reading from my messages file. Is there a way to handle these generic errors?
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleExceptions(Exception ex, Locale locale) {
String errorMessage = attemptToFecthMessageForCode(ex,locale);
//messageSource.getMessage(ExceptionProperty.UNEXPECTED_ERROR.getValue(), new Object[]{ex}, locale);
//ex.printStackTrace();
return new ResponseEntity<>(new RestMessage(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR);
}
public String attemptToFecthMessageForCode(Exception ex, Locale locale){
String msg = ex.getMessage();
try{
msg = messageSource.getMessage(ex.getMessage(), ex.getStackTrace(), locale);
}
catch (Exception e){
e.printStackTrace();
}
return msg;
}
Thanks in advance!.