有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有办法在exceptionHandler中传递第二个参数?

有一个可以引发异常的服务方法

if (NOT_FOUND) {
    throw new ResourceNotFoundException("Resource not found");
}

和ControllerAdvice与exceptionHandler

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity handleResourceNotFound(Exception ex) {
  return new ResponseEntity("your-error-message");
}

所以我需要将另一个字符串作为param传递,并从exceptionhandle访问它:

if (NOT_FOUND) {
    String param2 = "param2";
    throw new ResourceNotFoundException("Recource not found", param2);
}


@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Problem> handleResourceNotFound(Exception ex) {
  doomething(param2);
  return new ResponseEntity({your-error-message});
}

有什么办法吗


共 (3) 个答案

  1. # 1 楼答案

    是的,正如Abra所说,您可以创建自己的从ResourceNotFoundException继承的异常,并在其中添加其他参数。然后在异常处理程序中,您可以从异常中获取它:

    这可能就是课堂

    public class CustomException extends ResourceNotFoundException {
      private String otherParam;
    
      public CustomException(String message, String otherParam) {
         super(message);
         this.otherParam = otherParam
      {
       public getOtherParam() {
         return otherParam;
       }
    
    }
    

    然后你把它扔了

    throw new CustomException("Recource not found", param2);
    

    然后在异常处理程序中,您可以获得第二个参数

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Problem> handleResourceNotFound(CustomException ex) {
      doomething(ex.getOtherParam());
      return new ResponseEntity(ex.getMessage());
    }
    
  2. # 2 楼答案

    只要更新你的建议:

    @ExceptionHandler(ResourceNotFoundException.class)
    // public ResponseEntity handleResourceNotFound(Exception ex) {
    public ResponseEntity handleResourceNotFound(ResourceNotFoundException ex) {
      // ex contains all parameters that you need
      return new ResponseEntity("your-error-message");
    }
    
  3. # 3 楼答案

    我指的是error handle tutorial (chapter 6.3),在这里您可以看到异常处理程序的正确用法,就像您在代码片段中所做的那样

    你的方法有一个有趣的方面:

    Of course, we'll use the global exception handling mechanism that we discussed earlier to handle the AccessDeniedException as well:

    因此,异常处理程序的目的是处理各种异常的异常:全局异常处理。您将不知道异常被抛出的位置。因此,在处理程序端向异常处理程序添加额外的逻辑是没有意义的

    你应该在现有的基础上采取行动,而不是给处理者增加一个背包。这将需要一个小的archituetur变化,并在那里处理:

    if (NOT_FOUND) {
        String param2 = "param2";
        doomething(param2);
        throw new ResourceNotFoundException("Recource not found");
    }
    

    clean code-separation of concerns

    • 如果这是异常处理的一般方面,那么您已经掌握了一般信息

    • 如果它是一个特定的方面,那么它应该在发生的地方处理