Context: Java SpringBoot exposing REST apis
I have a RestControllerAdvice that is used to return a Response with the message of the exceptions that may occur during business logic:
@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class ExceptionRestController {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler({ FunctionalRuntimeException.class })
public DavinciApiResponse<Void> handleFunctionalRuntimeException(FunctionalRuntimeException exception) {
DavinciApiResponse<Void> response = ExceptionUtils.buildResponse(exception);
ExceptionUtils.logException(exception);
return response;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({ ValidationException.class,
ConstraintViolationException.class })
public <E extends Exception> DavinciApiResponse<Void> handleValidationException(E exception) {
DavinciApiResponse<Void> response = ExceptionUtils.buildResponse(exception);
ExceptionUtils.logException(exception);
return response;
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public DavinciApiResponse<Void> handleAllUncaughtException(Exception exception) {
DavinciApiResponse<Void> response = ExceptionUtils.buildResponse(exception);
ExceptionUtils.logException(exception);
return response;
}
}
Should the exception message be used by the frontend team to show it to the final user?
From my little working experience I would say yes (this is the approach that I have always seen), but I don’t really agree with it…
Example 1:
I need to develop a multi-language Web application (ENGLISH – FRANCH – SPANISH)
Should backend be language aware ?
I’m pretty sure the answer is NO. It is a frontend responsibility to show the page in the language specified by the user, so it is his job to show an appropriate error message to the user.
Example 2:
Backend is using open-source libraries that throws RuntimeExceptions.
In this case it is also not possible to manipulate the exception message directly, at most I have to wrap it by passing it as argument to a new Exception.
A possible solution I was thinking for handling multi language exception message is to create a new Microservice for handling Business Logic exceptions:
- frontend call API of Microservice A
- a business logic exception was thrown on the API, so it returns as response an object containing a messageCode (UNIQUE CODE for identifying the message), and messageParams (parameters of the message code)
- the frontend then call API of “Microservice Business Logic exceptions” passing as request an object containing messageCode, messageParams and the language
- the “Microservice Business Logic exceptions” returns the exception message translated to the required language, for example by extracting the message from database passing the messageCode.
How do you handle the exceptions message ?
What are the alternatives ?