SQLException is never thrown only global Exception

Viewed 39

I am trying to provoke error in MySql to get SQLException in spring but without succes. SQLException is never thrown only global Exception. I am tring to delete record typing a name witch is not aloud to delete and in MySql it is a error: "Error Code: 1451. Cannot delete or update a parent row.." This is in MySql and it should be like this. When I try it true controller I got 500 error response, just Exception and it should be SQLException.

I am putting code from delete method:

@Override
public void deleteCity(String name)throws SQLException {
    if(cityRepo.findByName(name)==null)throw new NullPointerException("No city with entered name");
    City city = cityRepo.findByName(name);
    cityRepo.delete(city);
}

Here is controller:

@DeleteMapping(path = "/city/delete")
public void deleteCity(@Valid @NotEmpty(message = "Name must not be empty")
                       @RequestParam(value = "name", required = true) String name) throws SQLException {
    cityService.deleteCity(name);
}

Global handler:

@ExceptionHandler(SQLException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public ResponseEntity<Object> handleArgumentException(SQLException sqlExc, WebRequest request) {
    log.error("SQL database exception occured - check database", sqlExc);

    return buildErrorResponse(sqlExc, HttpStatus.NOT_ACCEPTABLE, request);
}

I tried with my class like to extend SQLException but it is same behavior. Anyone knows the problem?

1 Answers

Should you try to put this at your CityService

@ExceptionHandler(SQLException.class)
public void handleSQLException() {}

It's will tell Spring Boot how to handle SQLException
hope it's work

Related