我是初学者。代码如下
@RestController
@RequestMapping("/channel")
public class ChannelController
{
@GetMapping("/getId/{participantId}/{walletType}")
Map<String,Object> getChannelId(@PathVariable Integer participantId , @PathVariable Integer walletType ){
return demoDAOImpl.getChannel(participantId, walletType);
}
}
当我点击http://localhost:8080/channel/getId///
时,它会返回默认的Whitelabel错误页面,其中包含
出现意外错误(type = Not Found,status = 404)。
我很困惑。我认为Spring MVC应该抛出MissingPathVariableException
。为什么回复404响应,找不到资源?
答案 0 :(得分:0)
您可以使用 @PathVariable(required = false)
并手动处理逻辑:
@RestController
@RequestMapping("/channel")
public class ChannelController
{
@GetMapping("/getId/{participantId}/{walletType}")
Map<String,Object> getChannelId(@PathVariable(required = false) Integer participantId , @PathVariable(required = false) Integer walletType) {
if (participantId == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Participant is required");
}
if (walletType == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Wallet type is required");
}
return demoDAOImpl.getChannel(participantId, walletType);
}
}
答案 1 :(得分:-1)
根据您的网址映射:您不能将其留空,如&#34; /// &#34;它必须是&#34; / number / number / &#34;
答案 2 :(得分:-1)
我猜你要的是自定义异常。那么你需要的是提供一个处理程序,你只需简单地扩展抽象类ResponseEntityExceptionHandler并覆盖方法handleMissingPathVariable。
一个例子:
@Override
protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
String error = ex.getParameter() + " parameter is missing";
ErrorMessageHandler error =message(HttpStatus.BAD_REQUEST, ex.toString(), error) ;
return new ResponseEntity<Object>(error, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}