2013-04-11 29 views
1

我用我的restful http api的spring mvc。请求参数可以按照要求进行注释如何在需要的rquest参数丢失时通知呼叫者?

@RequestParam(value = "group", required = true) String someParam 

当调用没有所需参数的api时,会返回一些丑陋的信息。

HTTP/1.1 400 Bad Request 
Content-Type: text/html;charset=ISO-8859-1 
Cache-Control: must-revalidate,no-cache,no-store 
Content-Length: 1380 
Server: Jetty(8.1.9.v20130131) 

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> 
<title>Error 400 Bad Request</title> 
</head> 
<body><h2>HTTP ERROR 400</h2> 
<p>Problem accessing /api/brokers. Reason: 
<pre>Bad Request</pre></p><hr /><i><small>Powered by Jetty://</small></i><br/> 
<br/> 

</body> 
</html> 

是可能捕获这些类型的错误,以便我可以通知调用者缺少什么。

回答

3

你需要捕捉MissingServletRequestParameterException

@ExceptionHandler(MissingServletRequestParameterException.class) 
public String missingParamterHandler(Exception exception) { 
    /*inspect and exception and obtain meaningful message*/ 
    return "default-error-view"; /*view name of your erro jsp*/ 
} 
+0

谢谢@NimChimpsky这个宝贵的答案......我解决我的问题,是由于这个帖子后MissingServletRequestParameterException 6小时研究,而在春季@ Responsebody服务电话 – 2014-09-19 05:41:54

0
@ResponseBody 
    @ExceptionHandler(MissingServletRequestParameterException.class) 
    public Object missingParamterHandler(Exception exception) { 
     // exception handle while specified arguments are not available requested service only. it handle when request is as api json service  
     return new HashMap() {{ put("result", "failed"); put("type", "required_parameter_missing");}}; 
    }