如何从HandlerMethodArgumentResolver返回HTTP响应

时间:2018-03-07 11:04:26

标签: http spring-mvc exception

我有一些控制器的方法:

@RequestMapping("/")
@AuthorizedRNUser
public Object index(UserStateVO userStateVO) {
    return userStateVO;
}

我也有UserlerVO参数的HandlerMethodArgumentResolver

public class UserStateArgumentHandlerResovler implements HandlerMethodArgumentResolver{

    @Autowired
    RNService service;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getMethod().isAnnotationPresent(AuthorizedRNUser.class) && methodParameter.getParameterType() == UserStateVO.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        UserStateVO userState = service.getUserState();
        if (isNull(userState))
            // here i need to return 403 HTTP response
            throw new RuntimeException("User is not allowed");
        return userState;
    }
}

如果UserStateVO为null,我需要返回403 HTTP响应,但我不知道是否可能?如何最好地检查UserStateVO并将其传递给控制器​​或返回HTTP响应?

1 个答案:

答案 0 :(得分:1)

使用与处理MVC exception-handling-in-spring-mvc

中的异常相同的方法

添加自定义例外,例如

public class BadRequestException extends RuntimeException {
  private static final long serialVersionUID = 1L;
  public BadRequestException(String message) {
    super(message);
  }
}

使用@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "User is not allowed")注释或使用

等方法添加@ControllerAdvice
@ExceptionHandler(value = { BadRequestException.class })
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ResponseBody
public Map<String, String> handleBadRequestException(BadRequestException e) {
   Map<String, String> retMessages = new HashMap<>();
   retMessages.put("message", e.getMessage());
   return retMessages;
}

剩下的只是抛弃它

if (isNull(userState))
        // here i need to return 403 HTTP response
        throw new BadRequestException("User is not allowed");
相关问题