Java – add new fields in body exception spring rest

I want to handle exceptions in the rest spring startup application I know that with @ controlleradvice and responseentity, I can return a custom object representing my error, but what I want is to add a new field to the body of the Exesting exception

I created a custom exception, which inherits runtimeException with an additional attribute and a string list:

@ResponseStatus(HttpStatus.CONFLICT)
public class CustomException extends RuntimeException {

    private List<String> errors = new ArrayList<>();

    public CustomException(List<String> errors) {
        this.errors = errors;
    }

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message,List<String> errors) {
        super(message);
        this.errors = errors;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }
}

In my controller, I just throw this custom exception:

@GetMapping("/appointment")
public List<Appointment> getAppointments() {
    List<String> errors = new ArrayList<>();
    errors.add("Custom message");
    throw new CustomException("This is my message",errors);
}

When I test my rest endpoint with postman, it seems that spring boot will not group my error fields. The response is:

{
  "timestamp": "2017-06-05T18:19:03","status": 409,"error": "Conflict","exception": "com.htech.bimaristan.utils.CustomException","message": "This is my message","path": "/api/agenda/appointment"
}

I can use @ controlleradvice to get custom objects. If I can get the "path" and "timestamp" fields from the exception, but these two properties have no getter

thank you.

Solution

OK! The following is the implementation of "path" and "timestamp" in defaulterrorattributes. You can also perform this operation in a custom implementation:

route:

String path = getAttribute(requestAttributes,"javax.servlet.error.request_uri");
if (path != null) {
    errorAttributes.put("path",path);
}

Timestamp:

errorAttributes.put("timestamp",new Date());

Error during spring startup. The customized document is here

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String,Object> getErrorAttributes(RequestAttributes requestAttributes,boolean includeStackTrace) {
            Map<String,Object> errorAttributes = super.getErrorAttributes(requestAttributes,includeStackTrace);
            // customize here
            return errorAttributes;
        }

   };
}

Alternatively, you can write a custom implementation:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String,boolean includeStackTrace) {
        Map<String,includeStackTrace);
        // customize here
        return errorAttributes;
    }
}

The errorattributes bean customizes the following error responses:

{
   "timestamp": 1413883870237,"status": 500,"error": "Internal Server Error","exception": "org.example.ServiceException","message": "somthing goes wrong","path": "/index"
}

You can use @ exceptionhandler to customize the "exception" attribute@ Controleradvice can be used for general custom exceptions across controllers To customize at the controller level, you can put them in the controller

In your case:

@ResponseStatus(value=HttpStatus.BAD_REQUEST,reason="Invalid Inputs")
    @ExceptionHandler(CustomException.class)
    private void errorHanlder() {
        //Log exception
    }


  public Map<String,boolean includeStackTrace) {
    Map<String,includeStackTrace);
    Throwable error = getError(requestAttributes);
    if (error instanceof CustomException) {
        errorAttributes.put("errorList",((CustomException)error).getErrors());
    }
    return errorAttributes;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>