Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-)

like image 585
Shotgun Avatar asked Oct 27 '25 09:10

Shotgun


1 Answers

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;
     }
}
like image 50
Aalkhodiry Avatar answered Oct 28 '25 23:10

Aalkhodiry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!