简体   繁体   中英

Validating Rest Controller URL in Spring boot

I am adding a new record in the Postman using the URI localhost:8080//insurance/service/add . Requirement - I want the application to throw an error in JSON mentioning an error code and customized message if any non-whitespace characters is after the URI. For example, if I want to add a record by using the URI such as localhost:8080//insurance/service/add? or localhost:8080//insurance/service/add* or anything like that, it should throw an error in JSON mentioning the error code and message. How should I proceed?

PS - new with spring boot.

@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!!!";

 }
}

You can use @RestControllerAdvice or @ControllerAdvice to properly handle exceptions with http status.

@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 is coustomised Class to generate customised error response. In this class you can handle any exception (customized too)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM