Search code examples
javaspringspring-mvcweb

Spring controller throwing HttpStatus.UNAUTHORIZED fires 500 Http error instead of 401


Here's the scenario : I created the following custom response exception, to fire the 401 Http Status :

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class HttpUnauthorizedException extends RuntimeException {

}

The controller that uses the exception :

@Controller
public UserController {
    @RequestMapping(value = "api/user")
    @ResponseBody

    public String doLogin(
                 @RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password) {
        if(userLoggedIn(String username, String password)) {
             return "OK";
        }
        else {
             throw new HttpUnauthorizedException();
        }
    }
   ...
}

Now when I try to access the controller to see the 401 exception, the server fires the Http error code 500 instead. But interestingly enough, when I try with the HttpStatus.NOT_FOUND it actually works, the server fires 404. Is there something I'm missing on here?

Thanks in advance :-)


Solution

  • First throw new HttpUnauthorizedException();

    then you can catch it at a normal controller that have @ControllerAdvice annotation

    @ControllerAdvice // To Handle Exceptions
    public class ExceptionController {
         //// ...........
    
         @ExceptionHandler({HttpUnauthorizedException.class})
         @ResponseBody
         @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
         Map<String, String> unauthorizedAccess(Exception e) {
             Map<String, String> exception = new HashMap<String, String>();
    
             log.error("unauthorized Access to the API: " + e.getMessage(), e);
             exception.put("code", "401");
             exception.put("reason", e.getMessage());
    
             return exception;
         }
    }