In my Spring boot project, we are parsing JWT token to get the claims & throwing InsufficientAuthenticationException as follows.
public String getIssuerClaim(String accessToken) throws AuthenticationException {
JWSObject jwsObject;
JWTClaimsSet claims;
try {
jwsObject = JWSObject.parse(accessToken);
claims = JWTClaimsSet.parse(jwsObject.getPayload().toJSONObject());
} catch (java.text.ParseException e) {
log.error("Token parsing exception. " + e.getMessage());
throw new InsufficientAuthenticationException("Invalid Token: " + e.getMessage());
}
return (String) claims.getClaim("SUB");
}
If there is a request arrived with null authorization header, this will throw this exception as it couldn’t parse the token which shows the Spring boot’s default internal server error.
I want to grab this error as part of my global exception handler and it is not getting inside the method at all.
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(InsufficientAuthenticationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected ResponseEntity < ErrorPayload > handleInsufficientAuthenticationException(
InsufficientAuthenticationException exception) {
ErrorPayload errorMessage = new ErrorPayload(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage());
log.error(errorMessage.toString(), exception);
return new ResponseEntity < > (errorMessage, getHttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I have tried with both @RestControllerAdvice
& @ControllerAdvice
. No luck yet.
I have updated the application.yaml as follows,
server:
error:
whitelabel:
enabled : false
error:
path: /error
Tried adding my custom error handler
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class MyErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
if (statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404";
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error-500";
}
}
return "error";
}
}
I kept breakpoint in all these classes and nowhere it is hitting. 🙁
Any suggestions?