尝试保存2次相同的条形码卡,方法saveBarcodecard (左侧图像)抛出错误:SQLIntegrityConstraintViolationException:“复制条目‘1-*- was 13’,用于键‘fcs_barcodecards.UK4ComplexKey’,该方法期望我被该方法拦截:handleExceptionInternal用于处理所有未具体实现但未实现的异常。
请注意:SQLIntegrityConstraintViolationException扩展了。扩展.异常
我需要实现一个自定义处理程序handleSQLIntegrityConstraintViolationException (请参阅下面的图2-绿色-)来解决这个问题。
我的简单问题是:这是为什么?)
谢谢你的回答,如果有的话:)
@Service
public class FcsBarcodecardServiceImpl implements FcsBarcodecardService {
@Autowired
FcsBarcodecardRepository fcsBarcodecardRepository;
@Autowired
private FcsClientRepository fcsClientRepository;
@Autowired
private FcsBarcodecardMapper fcsBarcodecardMapper;
@Override
public FcsBarcodecardResponse saveBarcodecard(Long clientId, FcsBarcodecard fcsBarcodecard) {
Optional<FcsClient> fcsClient = fcsClientRepository.findById(clientId);
if (!fcsClient.isPresent()) {
throw new UsernameNotFoundException("This client do not exists!");
}
fcsBarcodecard.setFcsClient(fcsClient.get());
return fcsBarcodecardMapper
.fromFcsBarcodecardToFcsBarcodecardResponse(
fcsBarcodecardRepository.save(fcsBarcodecard));
}
}
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final String VALIDATION_ERROR_CHECK_ERRORS_FIELD_FOR_DETAILS = "Validation error. Check 'errors' field for details.";
/**
* Predefined: A single place to customize the response body of all exception
* types.
*/
@Override
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Object> handleExceptionInternal(Exception exception, Object body, HttpHeaders headers,
HttpStatus status, WebRequest request) {
return buildErrorResponse(exception, FCS_EALLTYPES500, status, request);
}
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Object> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex,
WebRequest request) {
return buildErrorResponse(ex, FCS_EALLTYPES500, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
发布于 2022-05-06 16:15:33
ResponseEntityExceptionHandler#handleExceptionInternal()
是一个只自定义由@ExceptionHandler
在ResponseEntityExceptionHandler
中定义的异常类型的响应体的地方。在最新的Spring版本中,它们是
@ExceptionHandler({
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
MethodArgumentNotValidException.class,
MissingServletRequestPartException.class,
BindException.class,
NoHandlerFoundException.class,
AsyncRequestTimeoutException.class
})
显然,您的SQLIntegrityConstraintViolationException
不在其中,需要一个单独的异常处理程序来捕获和处理。
如果您希望有一个地方来处理任何期望,则必须使用例如@ExceptionHandler(Exception.class)
来专门定义异常处理程序。
https://stackoverflow.com/questions/72143402
复制相似问题