Rico Kahler
Rico Kahler

Reputation: 19242

How can I return a HTTP 400 response when a specific exception occurs?

I'm using spring MVC and with a relational database. One of the tables Spring writes to has a uniqueness constraint which works as expected.

Right now if a request comes in that violates that constraint the exception org.springframework.dao.DuplicateKeyException is thrown and an HTTP 500 response (internal server error) is returned, but really there is no issue with system but with the request of the user.

What is the most natural way to catch the exception and return a HTTP 400 (bad request)? I could actually catch it like so:

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<BaseMaterial> insert(@RequestBody BaseMaterial baseMaterial) {
    try {           
        baseMaterial.setId(UUID.randomUUID());
        baseMaterialService.insert(baseMaterial);
        return ResponseEntity.ok(baseMaterial);
    } catch (DuplicateKeyException e) {
        return ResponseEntity.badRequest().build();
    }
}

But then I'd have to do that for every one of my endpoints. I'd also prefer to use just the POJO without the ResponseEntity wrapper.

Thanks!

Upvotes: 3

Views: 3403

Answers (2)

Rico Kahler
Rico Kahler

Reputation: 19242

My apologies for answering my own question but I found what I was looking for on spring's blog.

In your controller class, create a method that will run when the desired exception is thrown and annotate it with ExceptionHandler and ResponseStatus:

@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation") // 409
public void conflict() {
    // code goes here
}

And that's it. No other changes!

Upvotes: 2

MatMat
MatMat

Reputation: 908

Or maybe it's actually a problem with the system/server. I'd say you should check for duplicates before inserting. Check if a row already exists with the given unique field and then throw an exception if true.

Upvotes: 1

Related Questions