javaspringspring-bootweblogic-10.x

Define custom error message in REST using Spring on Weblogic


I am hosting Spring Boot app on weblogic 10.3.6 for REST api I'd like to implement these 2 features:

  1. Whenever my custom exception occurs I would like to send a http response with message e.g. 500 - "request couldn't be parsed because of something..."
  2. Whenever any error is thrown I would like to get the stack trace that is usually printed to console (for debugging purposes)

I tried to solve the first part the following way:

@ControllerAdvice
public class ExceptionHandlerAdvice {


    @ExceptionHandler(MyException.class)
    public ResponseEntity handleException(MyException e) {

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

However as a response I only get 500 Internal Server Error with no message

As for the second part I tried simmilar approach but there was no error message either.

How can I solve this?

EDIT: The best I could achieve was removing ExceptionHandlerAdvice and using annotation on my exception class instead like this:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason="This is a message I'd like to send")

It works, but I have to add some variables from code to the message and this method does not allow it

EDIT2: This is a bit weird, perhaps a behavior of weblogic server, but when I set the httpStatus to HttpStatus.ACCEPTED I can see the message, if it is HttpStatus.Forbidden or any other 4xx error I just get the error without message


Solution

  • Create 'ResponseEntity' object with message and status and return it, it will display with error message.

    /**
     * HTTP_STATUS - 500 -Service Unavailable.
     * 
     * @param exception
     *            Catches the following: MyException
     * @return
     */
    @ExceptionHandler({ MyException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public static ResponseEntity<?> handleConnectionErrorResponse(MyException exception) {
        return new ResponseEntity<String>("Some error occurred at server", HttpStatus.INTERNAL_SERVER_ERROR);
    }