1

I use spring mvc for my restful http api. Request parameters can be annoted as required by

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

When calling the api without the required parameter, some ugly info returns.

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>

Is is possible to catch these kind of errors so that i can inform the caller what's missing.

kryger
  • 12,906
  • 8
  • 44
  • 65
qiuxiafei
  • 5,827
  • 5
  • 30
  • 43

2 Answers2

3

You need to catch 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*/
} 
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • Thank you @NimChimpsky for this valuable answer ...i solved my problem due to this post after 6 hours research of MissingServletRequestParameterException while service call in spring @ Responsebody – Janak Dhanani Sep 19 '14 at 05:41
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");}};
    } 
Janak Dhanani
  • 214
  • 4
  • 12