缺少@requestparam时自定义错误响应消息

时间:2014-04-23 12:36:10

标签: java spring spring-mvc

我已经在stackoverflow上查看了一堆现有页面,但这些都没有帮助:

How to customize @RequestParam error 400 response in Spring MVC

How to inform callers when required rquest parameter is missing?

我的问题非常相似:

  • 我的应用程序实际上是一个REST api,返回json / xml数据而不是html(即我不使用jsps,但编组将java bean转换为json / xml)
  • 当我使用必需参数查询URL时,我得到400状态,有效负载中没有任何内容,没有文本,nada。
  • 我想使用我在其他地方使用的ErrorResponse对象返回json / xml有效负载。
  • 我使用的是Spring 3.2.5
  • 我有一个控制器,它将URL映射到具有必需的方法 参数(candidateBillDay)

    @Controller
    public class AccountController extends WsController {
    
      private static final String JSP_CANDIDATE_PDD = "candidatepdd";
    
      @RequestMapping( value="/account/{externalId}/{externalIdType}/candidatepdd"
                     , method = RequestMethod.GET)
      public String getCandidatePaymentDueDateInfo( ModelMap model
                                                  , @PathVariable String externalId
                                                  , @PathVariable Integer externalIdType
                                                  , @RequestParam Integer candidateBillDay
                                                  , @RequestParam(required=false) Boolean includeCurrent ){
        ...
    
        model.addAttribute( CandidatePaymentDueDateResponse.ROOT_ELEMENT, ...));
    
        return JSP_CANDIDATE_PDD;
      }
    }
    
  • 我有一个捕获所有类型异常的异常处理程序,有一些逻辑可以为某些类型执行某些特定的位(instanceof):

    @ControllerAdvice
    public class BWSExceptionHandler extends ResponseEntityExceptionHandler {
      private static final Logger LOG = LoggerFactory.getLogger(BWSExceptionHandler.class);
      @ExceptionHandler(value = { Exception.class } )
      public ResponseEntity<Object> handleOtherExceptions(final Exception ex, final WebRequest req) {
        LOG.error("Uncaught Exception: ", ex);
        ErrorResponse resp = null;
        ...
        if( ex instanceof MissingServletRequestParameterException ){
          MissingServletRequestParameterException e = (MissingServletRequestParameterException)ex;
          resp = new ErrorResponse( Validatable.ERR_CODE_FIELD_NOT_POPULATED
                                  , String.format( Validatable.MSG_FIELD_IS_REQUIRED
                                                 , e.getParameterName()
                                                 )
                                  );
          httpStatusCode = HttpStatus.BAD_REQUEST;
        }
        if(resp==null){
          resp = new ErrorResponse(new ErrorElement("unknown_error", ex.getMessage()));
        }
        return handleExceptionInternal(ex, resp, new HttpHeaders(), httpStatusCode, req);
      }
    }
    

因此,当缺少参数时,这不会做任何事情。当我得到一个实际的例外(即帐户不存在)时,它确实捕获了异常并且作为例外工作。这让我认为没有抛出MissingServletRequestParameterException异常,根据我读过的文档,博客和stackoverflow页面应该抛出......

我还尝试实现一个扩展DefaultHandlerExceptionResolver并覆盖handleMissingServletRequestParameter方法但没有取得多大成功的类(遵循此博客:http://alexcuesta.wordpress.com/2011/05/11/error-handling-and-http-status-codes-with-spring-mvc/

我应该知道我做错了什么或者我应该探索哪些其他选择?

1 个答案:

答案 0 :(得分:2)

尝试在BWSExceptionHandler类中重写handleMissingServletRequestParameter方法。

@ControllerAdvice
public class BWSExceptionHandler extends ResponseEntityExceptionHandler {
  ...
  @Override
  protected ResponseEntity<Object> handleMissingServletRequestParameter(
      MissingServletRequestParameterException ex, HttpHeaders headers,
      HttpStatus status, WebRequest request) {
      // MissingServletRequestParameterException handling code goes here.
  }
  ...
  @ExceptionHandler(value = { Exception.class } )
  public ResponseEntity<Object> handleOtherExceptions(final Exception ex, 
    final WebRequest req) {
    ...
  }

}

希望这有帮助。

相关问题