Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

java - Recommended way of dealing with spring hibernate SQL errors

I have a post endpoint in my controller in spring that looks like so

@Autowired
private BookRepository bookRepository;

@PostMapping(path="/book")
public @ResponseBody BookEntity addBook(@RequestBody BookEntity bookEntity)
{
    return this.bookRepository.save(bookEntity);
}

Now, if invalid json data is submitted and the save function is called my console will output an error such as h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '1091209' for key 'isbn'

And the user will see a very non-user friendly api response.

Another issue this brings it seems is that an auto_incremented id is skipped e.g. I go 1,2,4, skipping 3 due the 3rd api call being the failing api call.

What is best practice for handling the above scenarios?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can define your own error handler which extends ResponseEntityExceptionHandler and catch db specific exception. Here is a code...

@RestControllerAdvice
@RequestMapping(produces = "application/json")
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    // This method handles constraint violation exception raised by DB. 
    // Similarly other type exceptions like custom exception and HTTP status related 
    //exception can be handled here.
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(ConstraintViolationException ex) {
    // write your own logic to return user friendly response 
   }

   // Below method is to handle _SqlExceptionHelper_ exception
    @ExceptionHandler(SqlExceptionHelper.class)
    @ResponseStatus(value = HttpStatus.CONFLICT)
    public Map<String, String> handleConstraintViolationException(SqlExceptionHelper ex) {
    // write your own logic to return user friendly response 
   }



}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...