Biggy_java2
Biggy_java2

Reputation: 1951

Spring mvc controller null return handler

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<Country> getListOfCountries() {

    return countryService.listAll();
}

It displays a json view of the object but if the service return null, then I want to display an error message, Any suggestions pls?

Upvotes: 0

Views: 2219

Answers (2)

Boris Treukhov
Boris Treukhov

Reputation: 17774

First of all, even if this does not directly answer the question, your objects should never ever return null instead of empty collections - you can find the reasoning in Effective Java 2nd Edition, Item 43 / p.201

So, if the situation when no countries were found is normal it must be processed by the client JS code that will check the count and display the respective message.

If something has gone wrong you can throw an exception(as Biju has pointed out +1) - I believe that it's the service who should throw the exception because it knows the reason why it happened, and not to return null anyway.

I'd like to add that in Spring 3.2(in pre Spring 3.2 returning response body is complicated) you can set an @ExceptionHandler that will both return JSON and set the HTTP status code which can be later processed by the client. I think that returning a custom JSON response with some error code is most optimal here.

    @RequestMapping("/test")
    @ResponseBody
    public List<Country> getListOfCountries() {
        //assuming that your service throws new NoCountriesFoundException();
            //when something goes wrong
            return countryService.listAll();
    }

    @ExceptionHandler(NoCountriesFoundException.class)
    ResponseEntity<String> test() {
        return new ResponseEntity<String>(
                "We are sorry, our server does not know any countries yet.",
                HttpStatus.I_AM_A_TEAPOT  );
    }

Then in the JS code, you can do specific processing depending on the returned status code.

Also, to avoid declaration of the same @ExceptionHandler in different controllers, in Spring 3.2 you can put @ExceptionHandler inside a @ControllerAdvice annotated class.

For details, see http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers and http://www.springsource.org/node/3738 for 3.2 specific things

Upvotes: 2

Biju Kunjummen
Biju Kunjummen

Reputation: 49935

You have a couple of options I think:

  1. If you return a null back, it will be returned as an empty string "", you can probably look for that and handle it.

  2. Return a wrapper type on top of your list, this way if the wrapped list is null something like this will be returned back to the client {"countries":null} which can be more easily handled at the javascript end.

  3. Throw an exception, which will propagate as a 500 status code back to the client, you can then have an error handler on the javascript side to handle this scenario.

Upvotes: 2

Related Questions