Currently Spring Boot will return INTERNAL_SERVER_ERROR
if OptimisticLockingFailureException thrown, It's better to use CONFLICT
instead, to archive that I need customize an ExceptionHandler
@ControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {
@ExceptionHandler(OptimisticLockingFailureException.class)
public void handleConflict(HttpServletRequest request, HttpServletResponse response, Exception e)
throws IOException {
response.sendError(HttpStatus.CONFLICT.value());
}
}
It would be great if Spring Boot handle it by default, or provide a way to map in properties, for example:
server.error.mapping:
"org.springframework.dao.OptimisticLockingFailureException": 409
Comment From: wilkinsona
Thanks for the suggestions.
It would be great if Spring Boot handle it by default
I don't think we can do this. Any 4xx response indicates that the client is at fault and we can't assume that's the case for every OptimisticLockingFailureException
. In some cases it will be a server-side problem and a pessimistic locking strategy should have been used.
Or provide a way to map in properties, for example
This is certainly concise. However, it feels a bit like programming by properties to me and I'm not too sure how generally useful it would be. Let's see what the rest of the team thinks.
Comment From: wilkinsona
The exception to HTTP status mapping part of this is a duplicate of https://github.com/spring-projects/spring-boot/issues/7349.
Comment From: philwebb
I think I'd prefer not not use properties for Exception -> Status Code mapping since they're not type safe. The HandlerExceptionResolver
might already work for general purpose mapping. I think that you can call response.sendError
and return a null
result.
Since we can't map OptimisticLockingFailureException
, and we don't want to add properties support, I think we should close this one and continue the status mapping discussions in #7349.