我已经在stackoverflow上查看了一堆现有页面,但这些都没有帮助:
How to customize @RequestParam error 400 response in Spring MVC
How to inform callers when required rquest parameter is missing?
我的问题非常相似:
我有一个控制器,它将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/)
我应该知道我做错了什么或者我应该探索哪些其他选择?
答案 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) {
...
}
}
希望这有帮助。