How return error message in spring mvc @Controller

user3378876 :

I am using methods like this

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<UserWithPhoto> getUser(@RequestHeader(value="Access-key") String accessKey,
                                     @RequestHeader(value="Secret-key") String secretKey){
    try{
        return new ResponseEntity<UserWithPhoto>((UserWithPhoto)this.userService.chkCredentials(accessKey, secretKey, timestamp),
                new HttpHeaders(),
                HttpStatus.CREATED);
    }
    catch(ChekingCredentialsFailedException e){
        e.printStackTrace();
        return new ResponseEntity<UserWithPhoto>(null,new HttpHeaders(),HttpStatus.FORBIDDEN);
    }
}

And I want to return some text message when exception occurs but now I just return status and null object. Is it possible to do?

hzpz :

As Sotirios Delimanolis already pointed out in the comments, there are two options:

Return ResponseEntity with error message

Change your method like this:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
                              @RequestHeader(value="Secret-key") String secretKey) {
    try {
        // see note 1
        return ResponseEntity
            .status(HttpStatus.CREATED)                 
            .body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
    }
    catch(ChekingCredentialsFailedException e) {
        e.printStackTrace(); // see note 2
        return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body("Error Message");
    }
}

Note 1: You don't have to use the ResponseEntity builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI).

Note 2: Don't use printStackTrace(), use a logger instead.

Provide an @ExceptionHandler

Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice like this:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(ChekingCredentialsFailedException.class)
    public ResponseEntity handleException(ChekingCredentialsFailedException e) {
        // log exception
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body("Error Message");
    }        
}

Note that methods which are annotated with @ExceptionHandler are allowed to have very flexible signatures. See the Javadoc for details.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Spring MVC - How to return simple String as JSON in Rest Controller

What to return if Spring MVC controller method doesn't return value?

Spring MVC controller return HTML

Return only string message from Spring MVC 3 Controller

How to return error status and validation errors from this Spring MVC controller?

Why message property return Null in Spring MVC

How to return custom error message in Spring Boot for /error page

How to return binary data instead of base64 encoded byte[] in spring mvc rest controller

Download or redirect with error message to another controller action in Spring web MVC

Return xml file from spring MVC controller

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

Spring MVC: How to return an image from controller?

How to return Bean class Object as JSON in Rest Controller in Spring MVC

How to return view after mvc controller action?

How to return message from MVC controller to AngularJS controller

How to show error message on same page in spring MVC

How to show alert message in mvc 4 controller?

How to return error message from MVC Web API that returns a Model?

Return a 302 status code in Spring MVC Controller

How to do localization of error message in controller

Error message is not displayed in the Spring MVC validator

Return XML in a Spring MVC controller

MVC: should Model return error message or error code

MVC 4 - Error message from controller is not being displayed in view

how to return two lists from controller class in spring mvc

Return Error or message of a view on another view in mvc

How to return error message from service to controller and then to client

Display a modal dialog with an error message when the error is generated in the MVC controller

Laravel - How to return the error message