小编典典

当缺少必需的rquest参数时,如何通知调用者?

spring-mvc

我将spring mvc用于宁静的http api。请求参数可以根据需要进行注释

@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>

有可能捕获到此类错误,以便我可以通知呼叫者所缺少的内容。


阅读 436

收藏
2020-06-01

共1个答案

小编典典

您需要捕获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*/
}
2020-06-01