How to handle exception thrown from HandlerInterceptor implementation class using DataFetcherExceptionResolverAdapter Resolver?

23 Views Asked by At

In our springboot application with graphql, we have RequestInterceptor as below in Springboot Application :

@Component
public class PrincipalRequestInterceptor implements HandlerInterceptor {

@Autowired
private Environment environment;

@Override
public boolean preHandle( HttpServletRequest request,HttpServletResponse response,Object handler) {
    
    String userId= request.getHeader(HttpHeader.X_USER_ID);

    --- Some Code ---
    if(StringUtil.isEmptyOrWhiteSpace(userId)){
        throw new UnauthorizedException(HttpStatus.UNAUTHORIZED.value(),"Unauthorized access: You do not have permission to perform this action.");
    }

    --- Some Code ---
    return true;
}

@Override
public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    --- Some Code ---
}

}

And have exception resolver class defined as below :

@Component
public class SomeExceptionResolver extends DataFetcherExceptionResolverAdapter {

@Override
protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
    if (ex instanceof UnauthorizedException unauthorizedException) {
        ErrorType errorType;
        if(unauthorizedException.getStatusCode()== HttpStatus.UNAUTHORIZED.value()){
            errorType = ErrorType.UNAUTHORIZED;
            return graphQLError(errorType, (UnauthorizedException) ex, env);
        }
        else {
            return GraphqlErrorBuilder.newError().build();
        }
    }
    return null;
}

private GraphQLError graphQLError(ErrorType errorType, UnauthorizedException ex,DataFetchingEnvironment env){
    return --- Some Code ---
}

}

However, whenever this UnauthorizedException() thrown from PrincipalRequestInterceptor, it's not getting handled by SomeExceptionResolver. If the same exception is thrown from RestController, its working fine.

How can we handle such exceptions thrown from interceptor using common resolver?

0

There are 0 best solutions below