How to customize response with http code in SpringBoot

1. the best simple way

if you want to customize your response message with YourDTOClass, then you should set value to DTO Class before returning with HttpStatus.XXX (OK, BAD_REQUEST, ACCEPT , .....)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new YourDTOClass());
httpcode : 400
Json String is converted from AuthToken object


2. the next way

this way similar to the above one

return new ResponseEntity<>(new YourDTOClass(), HttpStatus.ACCEPTED);

3. Spring way with throw exception

If you only want to response http code and message then you should select this way

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "your message here");
then httpCode = 400 and  the response as below by spring's template
{
    "timestamp": "2019-02-14T09:55:36.477+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Code or Type is null",
    "trace": "org.springframework.web.server.ResponseStatusException: 400 BAD_REQUEST \"Code or Type is null\"\r\n\tat com.mp.ocr.BpoOcrBeApplication.greeting(BpoOcrBeApplication.java:58)\r\n\tat  .....",
    "path": "/ocr/greeting"
}

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch