在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作为参数传递的情况吗?

推荐答案

我相信是Spring MVC can inject many arguments in the exception handler method signature个,其中一个是HandlerMethod:

@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity dataIntegrityViolantionException(final DataIntegrityViolationException e, HandlerMethod handlerMethod) {

  // you can get the information you need with
  String message = handlerMethod.getShortLogMessage();

  // or extract more precise information
  Method method = handlerMethod.getMethod();

}

Java相关问答推荐

伪类focus-in不适用于PFA中的选项卡

Character::Emoji不支持带数字的字符吗?

使用传递的参数构造异常的Mockito-doThrow(或thenThrow)

这是什么Java构造`(InputStream Is)->;()->;{}`

基于调车场算法的科学计算器

类型集合的Jackson JsonNode:类型引用的对象读取器应该是Singleton吗?

Sack()步骤中的合并运算符未按预期工作

在向WebSphere中的文档添加元素时iText挂起

如何在代码中将行呈现在矩形前面?

如何在构建Gradle项目时排除com.google.guava依赖项的一个变体

如何使用log4j2(Json)记录由";异常引起的所有";?

如何从HttpResponse实例获取Entity对象的内容?

Android Studio模拟器没有互联网

对角线填充二维数组

在不使用instanceof或强制转换的情况下从父类变量调用子类方法

在Java中将.GRF转换为图像文件

Win32函数的JNA绑定DwmGetColorizationColor返回E_INVALIDARG错误

Maven-Dependency-Plugin 3.6.+开始查找在依赖关系:分析目标期间找到的新的使用的未声明依赖关系

控制器建议异常处理

在java中使用SevenZip.openArchive方法后无法删除文件