java - 在 Spring Boot 中验证 Rest Controller URL
问题描述
我正在使用 URI 在 Postman 中添加新记录localhost:8080//insurance/service/add
。要求 - 如果在 URI 之后有任何非空白字符,我希望应用程序在 JSON 中引发错误,提及错误代码和自定义消息。例如,如果我想使用诸如localhost:8080//insurance/service/add?
或之类的 URI 添加记录localhost:8080//insurance/service/add*
,它应该在 JSON 中抛出一个错误,提及错误代码和消息。我应该如何进行?
PS - 全新带弹簧靴。
@RestController
@RequestMapping("insurance/service")
public class InsuranceController{
@Autowired
Insurance_Service service;
// Create New Insurance
@PostMapping(path="/add", produces = "application/json")
public String addInsurance(@RequestBody (required=false) Insurance insurance ) {
if(insurance==null)
throw new MissingQueryParam();
this.service.addInsurances(insurance);
return "Insurance added successfully!!!";
}
}
解决方案
您可以使用@RestControllerAdvice 或@ControllerAdvice 正确处理具有http 状态的异常。
@RestControllerAdvice
public class WebRestControllerAdvice {
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseMsg handleNotFoundException(Throwable ex) {
ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
return responseMsg;
}
}
ResponseMsg 是定制的类,用于生成自定义的错误响应。在此类中,您可以处理任何异常(也可以自定义)
推荐阅读
- embedded - 如何正确清除 LPC17xx 中未决的外部中断?
- php - Auth::login() 无法正常工作 laravel 5.7
- java - 为什么我看到枚举常量的字段值确实被序列化/反序列化?在哪种情况下,究竟什么没有在枚举中序列化?
- reactjs - 为什么我的反应函数返回 [object,object]
- mysql - SELECT Where ID in (List of IDs) 并限制MySQL中每个ID的记录
- java - 来自 ArrayList 的 ArrayList 的唯一集合
- java - 我怎么做才能让这个框架中的圆圈实际上自动移动?
- c# - 在这种情况下是否有另一种添加 Console.WriteLine() 的方法
- php - 在窗口 10 中安装 laravel 安装程序时出错
- vue.js - 创建组件并附加到父级的 Vue 指令