Recommended way of dealing with spring hibernate SQL errors

后端 未结 1 1523
忘掉有多难
忘掉有多难 2020-12-22 01:24

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

@Autowired
private BookRepository bookRepository;

@PostMapping(path=\"/book\")
public @         


        
1条回答
  •  一整个雨季
    2020-12-22 02:07

    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 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 handleConstraintViolationException(SqlExceptionHelper ex) {
        // write your own logic to return user friendly response 
       }
    
    
    
    }
    

    0 讨论(0)
提交回复
热议问题