首页 > 解决方案 > 在 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!!!";

 }
}

标签: javaspringspring-boot

解决方案


您可以使用@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 是定制的类,用于生成自定义的错误响应。在此类中,您可以处理任何异常(也可以自定义)


推荐阅读