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.
ResponseEntity<Object>
or to aResponseEntity<?>
. Instead of passing anull
argument for your error case, pass in aString
. Spring is smart enough to see theString
and write it as text to the response body. Alternatively, provide a@ExceptionHandler
that will handle the exception itself and have your handler throw the exception. – Rotator