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

后端 未结 7 1939
别跟我提以往
别跟我提以往 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:18

    If you omit the 'reason' attribute in the @ResponseStatus annotation on a custom exception,

    @ResponseStatus(value = HttpStatus.CONFLICT)  // 409
    public class ChildDataExists extends RuntimeException {
    ...
    

    then throw the exception

    throw new ChildDataExists("Can't delete parent if child row exists.");
    

    The exception's message comes through as the 'message' of the 'data' in the JSON output. It seems the 'reason' in the annotation overrides the custom behavior.

提交回复
热议问题