Bill_Data23
Bill_Data23

Reputation: 659

How to return a error message in a method that return a ResponseEntity in Spring MVC using @ControllerAdvice

I'm working on a web app using Spring MVC and AngularJS, I'm creating a Rest API that returns ResponseEntities that contains JSON strings.

I want to be able when an Exception happens to return a string that contains the error cause to my view and then show this error with a modal in AngularJS, I created a Class with the @ControllerAdvice annotation and in this class I defined a method with my custom exception like this

@ControllerAdvice
public class GlobalExceptionHandlerController {

@ExceptionHandler(PersonalException.class)
public String handleCustomExceptionRazon(PersonalException ex) {

    String errorMessage = "custom error";


    return errorMessage;
}
}

I have the following interface

public interface ClientDAO {

public void insertCLiente(Client client) throws PersonalException
}

And in my implementation

@Override
public void insertCLiente(Client client) throws PersonalException{

//method implementation
 if (searchCLiente(client.name())) {
        throw new PersonalException("client aleady exists");
    } else {
//method implementation
}
}

My searchClient Method

public boolean searchClient(String name) {
try {
    //method implementation

} catch (DataAccessException dataAccessException) {
        System.out.println("");
        dataAccessException.printStackTrace();
    } catch (Exception e) {
        System.out.println("");
        e.printStackTrace();
    }
  //method implementation
}

My Client Controller

@Autowired
    ClientDAO clientDAO;

@RequestMapping(value = "/client/", method = RequestMethod.POST)
public ResponseEntity<Void> createClient(@RequestBody final String DTOClientData, UriComponentsBuilder ucBuilder) {

//here I parse the JSON data and create my Client object

   //here I dont know how can I return the error message

clientDAO.insertClient(client);

    }

My custom Exception

public class PersonalException extends Exception {

public PersonalException (String msg) {
    super(msg);
}

}

I don't know un my clientController method createClient how can I return an execption of the type PersonalException that I created

Upvotes: 3

Views: 13028

Answers (1)

Sundararaj Govindasamy
Sundararaj Govindasamy

Reputation: 8495

//here I dont know how can I return the error message

Just throw the exception from Controller.

@RequestMapping(value = "/client/", method = RequestMethod.POST)
public ResponseEntity<Void> createClient(@RequestBody final String DTOClientData, UriComponentsBuilder ucBuilder) throws PersonalException {

You can return error message in GlobalExceptionHandlerController like this...

  /**
* REST exception handlers defined at a global level for the application
**/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { PersonalException.class })
    protected ResponseEntity<RestResponse> handleUnknownException(PersonalException ex, WebRequest request) {
       LOGGER.error(ex.getMessage(), ex);

       return new ResponseEntity<RestResponse>(new RestResponse(Boolean.FALSE, ImmutableList.of("Exception message"), null), HttpStatus.INTERNAL_SERVER_ERROR);
     }

Now, you might have noticed that we are not handling the Exception even in the Controller. Instead, we are Throwing it in the declaration hoping that somewhere we have handled this exceptional case gracefully showing the User a nice looking Toaster message.

The question may remains – Where the hell i am handling the Exception? It is handling by the @ExceptionHandler in GlobalExceptionHandlerController .

Upvotes: 1

Related Questions