Rest API exception handling

Hi Team,

There was a post to resolve exception handling of Rest API here, but I found 2 issues using CUBA 7.2.10 and Rest-api 7.2.2.

  • First is using the similar code in #55 fix, create a custom exception with @supportedByClient annotation, the server will report:
com.haulmont.cuba.core.sys.serialization.SerializationException: Failed to deserialize object type

And in postman I got below result, with no useful message from backend:

{
    "error": "Server error",
    "details": ""
}
  • Second test is using system Exception type, for example, IllegalStateException, the same result got from postman:
{
    "error": "Server error",
    "details": ""
}

I debugged the second case, found the fix in #55 returns ex.getCause(), but the object in stack is as below:

Attached is a demo project:
restex.zip (82.0 KB)

Thank you for reporting the problem. We have created issues
No useful message from backend in case invoke CustomException/SystemException
and
SerializationException: Failed to deserialize object type in case custom exception with @supportedByClient

Hi.

Information about the the first issue:
We found that the custom exception declared in the wrong package. Exception classes should be declared in the global module.
https://doc.cuba-platform.com/manual-latest/exception_classes.html

Information about the second issue:
If you want to see the useful detailed message for the custom exception you need to create a handler for the exception. For system exceptions, we don’t provide a detailed message about the server error.

You can create an exception handler through the Spring mechanisms. The class should declare in the ‘web’ module
Hadler example:

@ControllerAdvice("com.haulmont.addon.restapi.api.controllers")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomRestControllerExceptionHandler {

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

    @ExceptionHandler(CustomHttpClientErrorException.class)
    @ResponseBody
    public ResponseEntity<ErrorInfo> handleException(Exception e) {
        log.error("Exception in REST controller", e);
        CustomHttpClientErrorException ex = (CustomHttpClientErrorException) e;
        ErrorInfo errorInfo = new ErrorInfo(ex.getStatusCode().getReasonPhrase(), ex.getStatusText());
        return new ResponseEntity<>(errorInfo, ex.getStatusCode());
    }
}

Use the current handler you can get a useful message.