在Spring Boot3中,我使用Controller Advice
来处理数据库唯一性异常,并创建自定义错误消息,我可以在JSON和日志(log)中传递该消息.
我想添加来自MethodHandler的信息,这样我还可以记录/添加有异常的URI和控制器到自定义消息.
这是迄今为止的设置方式:
Controller个
/**
* Update Car (PUT)
*/
@PutMapping(value = "/{id}", consumes = "application/json")
ResponseEntity<CarCreateDto> updateCarDto(@Valid @RequestBody CarCreateDto updateCar, @PathVariable Long id) {
CarCreateDto Car = CarService.updateCar(updateCar, id);
return new ResponseEntity<>(Car, HttpStatus.OK);
}
}
Exception Handler个
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity dataIntegrityViolantionException(final DataIntegrityViolationException e) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(df);
ErrorMessage errorMessage = new ErrorMessage();
String mostSpecificCauseMessage = e.getMostSpecificCause().getMessage();
if (e.getCause().getCause() instanceof SQLIntegrityConstraintViolationException) {
try {
String jsonMessage = objectMapper.writeValueAsString(errorMessage.builder()
.reasonCode(ErrorMessage.ReasonCode.NAME_ALREADY_EXISTS)
.message(mostSpecificCauseMessage)
.timeStamp(df.format(System.currentTimeMillis()))
.build());
return new ResponseEntity<>(jsonMessage, HttpStatus.CONFLICT);
} catch (JsonProcessingException ex) {
throw new RuntimeException(ex);
}
}
return new ResponseEntity<>("Unknown Data Integrity Violation Exception with message : " +mostSpecificCauseMessage, HttpStatus.UNPROCESSABLE_ENTITY);
}
示例here与我想要做的非常相似--但是它没有显示如何捕捉控制器and上的异常,将其传递给相关的HandlerMethod
实例,以便我可以添加:
Class ControllerName = handlerMethod.getMethod().getDeclaringClass();
String MethodName = handlerMethod.getMethod().getName();
错误消息的控制器名称和方法名称.
这仅仅是向控制器方法添加一个try Catch并将HandlerMethod作为参数传递的情况吗?