springexceptiongroovyerror-handlingcontroller-advice

Spring ControllerAdvice global exception handler not returning response


I have a Groovy Spring Boot microservice that returns a list of posts. Requests come into the controller, the controller invokes a method in a service class, and if no posts are found, a custom error message is thrown.

I've created a controller annotated with @ControllerAdvice that I want to intercept errors, and a handler specific to the custom error. It should return a POJO. At present the ControllerAdvice handler is being invoked, but the response from the microservice is a 500 error

The controller

@RequestMapping(value ='getCommentList', method = RequestMethod.POST)
def getCommentList(@RequestBody requestParams) {
    def response
    String userId = requestParams.userId
    String uuid = requestParams.uuid
    response = commentService.findCommentsByUserIdAndUuid(userId, uuid)
}

The service method

def findCommentsByUserIdAndUuid(String userId, String uuid) {
    User user = userRepository.findByUserId(userId)
    Long userId = tenant?.id
    List responses = commentRepository.findCommentsByUserAndUuidNotDeleted(userId, uuid)
    if (responses.size() == 0) {
        throw new CommentsNotFoundException()
    } else {
        def data = JsonOutput.toJson(retMap)
        return data
    }
}

the custom exception class package com.news.exception

class CommentsNotFoundException extends Exception {
    String errorMessage
    def dataReturned

    public commentsNotFoundException() {
       NewsFeedMessage.buildRequestErrorMessageWithData(errorMessage, dataReturned)
    }
}

The POGO to be returned

package com.news.utils

import org.springframework.http.HttpStatus

class NewsFeedMessage {
    int httpStatus
    String type
    String message
    def dataReturned
    def subMessages = []

    static NewsFeedMessage buildRequestErrorMessageWithData(mainMessage, data) {
        return new NewsFeedMessage(
            httpStatus: 400,
            message: mainMessage,
            dataReturned: data
        )
    }
}

And the global exception handler with@ControllerAdvice annotation

package com.news.exception

import com.newa.utils.NewsFeedMessage
import org.springframework.boot.configurationprocessor.json.JSON
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(CommentsNotFoundException.class)
    public NewsFeedMessage handleException() {
        def response = NewsFeedMessage.buildRequestErrorMessageWithData("testing 1234", [])
        //return response as JSON
    }
}

When debugging, The code gets as far as

        def response = NewsFeedMessage.buildRequestErrorMessageWithData("testing 1234", [])

However nothing is returned. The returned message using Postman is:

{
    "timestamp": "2020-10-23T16:27:35.572+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "No message available",
    "path": "/comment/getCommentList"
}

Is there anything here that is glaringly wrong?


Solution

  • I think NewsFeedMessage is not supported return type. Check ExceptionHandler docs and there is a block about supported return types. Try returning a ResponseEntity<>(new NewsFeedMessage()).