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

时间:2019-02-01 07:02:38

标签: java spring spring-boot

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

这是我的代码

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();
    }
}

ApplicationExceptionHandler.java

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()));
  }
}

AuthFilterRegistration.java

@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();
  }

}

ErrorEntity.java

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;
  }

}

使用这些代码,我要遇到这样的异常错误

{
  "numericErrorCode": 2001,
  "errorCode": "errors.net.myproject.platform.unauthorized",
  "errorMessage": "unauthorized"
}

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

{
  "timestamp": "2019-02-01T04:41:14.337+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "unauthorized",
}

从示例中可以明显看出,我无法完全覆盖默认的Java异常。仅成功更改的消息部分。我在这里想念什么吗?

1 个答案:

答案 0 :(得分:4)


import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {

@ResponseBody
@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()));
}

@ResponseBody
@ExceptionHandler(RetrievedProfileException.class)
public ResponseEntity<ErrorEntity> applicationexception(final RetrievedProfileException e) {
    ErrorEntity errorEntity = new ErrorEntity(e.getNumericErrorCode(), e.getErrorCode(), e.getErrorMessage());
    return new ResponseEntity<>(errorEntity, HttpStatus.valueOf(e.getHttpStatus()));
}

我只是扩展了此类org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler,因为它有先决条件

第二,我使用了@ControllerAdvice

最后我用了@ResponseBody

以这种方式使用异常处理程序,此外,您还应该以this方式覆盖异常。