Java 如何使自定义异常处理程序正常工作

Java 如何使自定义异常处理程序正常工作,java,spring,spring-boot,Java,Spring,Spring Boot,我想为我的应用程序使用自定义异常处理程序。但是,它不能正常工作 这是我的密码 AuthenticationFilter.java @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!bAuthorize) { chain.doFilter

我想为我的应用程序使用自定义异常处理程序。但是,它不能正常工作

这是我的密码

AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    if (!bAuthorize) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest req = (HttpServletRequest) request;

    String namespace = getPathParamFromRequest(req, NAMESPACE_PATH_PREFIX);
    String userId =  getPathParamFromRequest(req, USER_PATH_PREFIX);


    AuthContext auth = null;
    RequestPathContext rpc = pathsList.getMatchingContext(req.getRequestURI(), HttpMethod.valueOf(req.getMethod()));
    if (rpc != null)
        auth = rpc.getAuthContext();

    if (auth != null) {
        // Authentication process
    } else {
        throw new UnauthorizedException();
    }
}
public class ApplicationExceptionHandler {
  @ExceptionHandler(UnauthorizedException.class)
  public ResponseEntity<ErrorEntity> applicationxception(final UnauthorizedException e) {
    ErrorEntity errorEntity = new ErrorEntity(e.getNumericErrorCode(), e.getErrorCode(), e.getErrorMessage());
    return new ResponseEntity<>(errorEntity, HttpStatus.valueOf(e.getHttpStatus()));
  }
}
@Configuration
public class AuthFilterRegistration {

  @Autowired
  private ApplicationContext context;

  @Bean
  public FilterRegistrationBean<AuthenticationFilter> loggingFilter() {
    FilterRegistrationBean<AuthenticationFilter> registrationBean
            = new FilterRegistrationBean<>();

    registrationBean.setFilter(context.getBean(AuthenticationFilter.class));
    registrationBean.addUrlPatterns( "/public/*");

    return registrationBean;
  }

  @Bean
  public AuthenticationFilter getAuthFilter() {
    return new AuthenticationFilter();
  }

  @Bean
  public ApplicationExceptionHandler getErrorHandler() {
    return new ApplicationExceptionHandler();
  }

}
public class ErrorEntity extends BaseErrorEntity {

  String errorMessage;

  Map<String, String> messageVariables;

  public ErrorEntity() {
  }

  public ErrorEntity(int numericErrorCode, String errorCode, String errorMessage) {
    this(numericErrorCode, errorCode, errorMessage, null);
  }

  public ErrorEntity(int numericErrorCode, String errorCode, String errorMessage, Map<String, String> messageVariables) {
    this.numericErrorCode = numericErrorCode;
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
    this.messageVariables = messageVariables;
  }

}
ApplicationExceptionHandler.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    if (!bAuthorize) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest req = (HttpServletRequest) request;

    String namespace = getPathParamFromRequest(req, NAMESPACE_PATH_PREFIX);
    String userId =  getPathParamFromRequest(req, USER_PATH_PREFIX);


    AuthContext auth = null;
    RequestPathContext rpc = pathsList.getMatchingContext(req.getRequestURI(), HttpMethod.valueOf(req.getMethod()));
    if (rpc != null)
        auth = rpc.getAuthContext();

    if (auth != null) {
        // Authentication process
    } else {
        throw new UnauthorizedException();
    }
}
public class ApplicationExceptionHandler {
  @ExceptionHandler(UnauthorizedException.class)
  public ResponseEntity<ErrorEntity> applicationxception(final UnauthorizedException e) {
    ErrorEntity errorEntity = new ErrorEntity(e.getNumericErrorCode(), e.getErrorCode(), e.getErrorMessage());
    return new ResponseEntity<>(errorEntity, HttpStatus.valueOf(e.getHttpStatus()));
  }
}
@Configuration
public class AuthFilterRegistration {

  @Autowired
  private ApplicationContext context;

  @Bean
  public FilterRegistrationBean<AuthenticationFilter> loggingFilter() {
    FilterRegistrationBean<AuthenticationFilter> registrationBean
            = new FilterRegistrationBean<>();

    registrationBean.setFilter(context.getBean(AuthenticationFilter.class));
    registrationBean.addUrlPatterns( "/public/*");

    return registrationBean;
  }

  @Bean
  public AuthenticationFilter getAuthFilter() {
    return new AuthenticationFilter();
  }

  @Bean
  public ApplicationExceptionHandler getErrorHandler() {
    return new ApplicationExceptionHandler();
  }

}
public class ErrorEntity extends BaseErrorEntity {

  String errorMessage;

  Map<String, String> messageVariables;

  public ErrorEntity() {
  }

  public ErrorEntity(int numericErrorCode, String errorCode, String errorMessage) {
    this(numericErrorCode, errorCode, errorMessage, null);
  }

  public ErrorEntity(int numericErrorCode, String errorCode, String errorMessage, Map<String, String> messageVariables) {
    this.numericErrorCode = numericErrorCode;
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
    this.messageVariables = messageVariables;
  }

}
这是
ErrorEntity
的实例,但我得到了这个输出

{
  "timestamp": "2019-02-01T04:41:14.337+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "unauthorized",
}
从这个例子可以清楚地看出,我不能完全覆盖默认的Java异常。只有成功更改的消息部分。我错过了什么吗?


导入org.springframework.http.ResponseEntity;
导入org.springframework.web.bind.annotation.ControllerAdvice;
导入org.springframework.web.bind.annotation.ExceptionHandler;
导入org.springframework.web.bind.annotation.ResponseBody;
导入org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@控制器建议
公共类ApplicationExceptionHandler扩展了ResponseEntityExceptionHandler{
@应答器
@ExceptionHandler(UnauthorizedException.class)
公共响应性申请例外(最终未经授权的例外情况e){
ErrorEntity ErrorEntity=新的ErrorEntity(e.GetNumericeErrorCode(),e.getErrorCode(),e.getErrorMessage());
返回新的ResponseEntity(errorEntity,HttpStatus.valueOf(e.getHttpStatus());
}
@应答器
@ExceptionHandler(RetrievedProfileException.class)
公共响应权限应用程序异常(最终检索的配置文件异常e){
ErrorEntity ErrorEntity=新的ErrorEntity(e.GetNumericeErrorCode(),e.getErrorCode(),e.getErrorMessage());
返回新的ResponseEntity(errorEntity,HttpStatus.valueOf(e.getHttpStatus());
}

我只是扩展了这个类
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
,因为它的预使用

其次,我用

最后我用了

以这种方式使用异常处理程序,并且您应该以这种方式重写异常。


导入org.springframework.http.ResponseEntity;
导入org.springframework.web.bind.annotation.ControllerAdvice;
导入org.springframework.web.bind.annotation.ExceptionHandler;
导入org.springframework.web.bind.annotation.ResponseBody;
导入org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@控制器建议
公共类ApplicationExceptionHandler扩展了ResponseEntityExceptionHandler{
@应答器
@ExceptionHandler(UnauthorizedException.class)
公共响应性申请例外(最终未经授权的例外情况e){
ErrorEntity ErrorEntity=新的ErrorEntity(e.GetNumericeErrorCode(),e.getErrorCode(),e.getErrorMessage());
返回新的ResponseEntity(errorEntity,HttpStatus.valueOf(e.getHttpStatus());
}
@应答器
@ExceptionHandler(RetrievedProfileException.class)
公共响应权限应用程序异常(最终检索的配置文件异常e){
ErrorEntity ErrorEntity=新的ErrorEntity(e.GetNumericeErrorCode(),e.getErrorCode(),e.getErrorMessage());
返回新的ResponseEntity(errorEntity,HttpStatus.valueOf(e.getHttpStatus());
}

我只是扩展了这个类
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
,因为它的预使用

其次,我用

最后我用了


以这种方式使用异常处理程序,并且您应该以这种方式重写异常。

如果我没有弄错的话,如果您使用这样的方法创建ExceptionHandler,那么它们只适用于它们所在的类中抛出的异常defined@Stultuske那么,您的意思是说异常也应该在
AuthenticationFilterclass?不,我的意思是,如果你想像你那样实现@ExceptionHandler,你应该把它放在抛出异常的类中。但是我没有看到任何方法真正抛出这些异常。我想我在
AuthenticationFilter
类的else块中抛出了
UnauthorizedException
。或者我在做什么它错了吗?@RafiRamadhan但你的方法签名并不表明你的方法可以抛出该异常?如果我没有弄错的话,如果你用这样的方法创建ExceptionHandler,它们只对它们所在的类中抛出的异常有效defined@Stultuske那么,您的意思是异常也应该在
Authenti中定义吗cationFilter
类?不,我的意思是,如果你想像你那样实现@ExceptionHandler,你应该在抛出异常的类中使用它。但是我没有看到任何方法真正抛出这些异常,我想我在
AuthenticationFilter
类的else块中抛出了
UnauthorizedException
。还是我做错了?@RafiRamadhan,但是你的方法签名并不表明你的方法可以抛出该异常?你可能想添加你所更改的内容以及它的不同之处。我只是扩展了这个类
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
,因为我使用了它的pre-requesite我曾经检查过这篇文章。也许这会对你有所帮助。@Rafiramadhan你可能想添加你所更改的内容以及它的不同之处。我只是扩展了这个类
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
,因为我第二次使用了它的pre-requse,最后一次使用了它。也许这会有帮助p你。@RafiRamadhan