REST API custom exception handling

Hi Cuba Team,

I used a POST request to http://localhost:8080/app/rest/v2/entities/Project$Entity to insert a record in a Postgresql table. On this table, I have a trigger that validates data and raises a PSQL Exception if some specific data is inserted. I want to expose this error message to the client (as it is), because now I get only:

    "error": "Server error",
    "details": ""

What is the best approach to achieve this?
(I saw the method that returns the above message is: handleException of the class: com.haulmont.restapi.controllers.RestControllerExceptionHandler)


1 Like

you can create your own exception handler that will override the standard behavior. Something like this:

public class MyRestControllerExceptionHandler {

    private Logger log = LoggerFactory.getLogger(MyRestControllerExceptionHandler.class);

    public ResponseEntity<ErrorInfo> handleException(Exception e) {
        log.error("Exception in REST controller", e);
        ErrorInfo errorInfo = new ErrorInfo("Server error", e.getMessage());
        return new ResponseEntity<>(errorInfo, HttpStatus.INTERNAL_SERVER_ERROR);

This ControllerAdvice has higher priority than a standard one, so it will handle your exceptions.

Also you will need to add a package with your own controller advice to the spring component-scan. You’ll have to create a rest-dispatcher-spring.xml file in the main directory of your web module (e.g. The file should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <!-- Define a base package for your controllers-->
    <context:component-scan base-package=""/>


Your exception handler class must be under the directory.

Then register the rest-disptacher-spring.xml file in the

cuba.restSpringContextConfig = +com/company/myproject/rest-dispatcher-spring.xml
1 Like

Thank you

Hello, I have implemented the class as suggested, and it works. The problem I have is that now pertinent
logging is not shown neither in the File nor the Console appender. Any ideas ?

Hi @gorbunkov
can I create my own exception handler for Oauth2AuthenticationEntryPoint? If the token expires the default response looks like:
“error”: “invalid_token”,
“error_description”: “Invalid access token: a2329f32-a503-40b0-aa0f-6eaba496b88b”
I want another json structure in the response. Or Is there an other way to rename “error” to “errorKey” or such stuff?

Make sure your exception is annotated with @SupportedByClient or it will be rethrown and you cant catch it