In Spring 3 is it possible to dynamically set the reason of @ResponseStatus?

后端 未结 7 1954
别跟我提以往
别跟我提以往 2021-02-05 02:01

I have a custom exception class annotated to return a given HttpStatus:

@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason=\"Invalid parameter\")
         


        
7条回答
  •  春和景丽
    2021-02-05 02:07

    Since spring 5.0, you can use the ResponseStatusException which is available

    // From https://www.baeldung.com/spring-response-status-exception
    @GetMapping("/actor/{id}")
    public String getActorName(@PathVariable("id") int id) {
        try {
            return actorService.getActor(id);
        } catch (ActorNotFoundException ex) {
            throw new ResponseStatusException(
              HttpStatus.NOT_FOUND, "Actor Not Found", ex);
        }
    }
    

提交回复
热议问题