如何在Springboot中正确返回Response

问题描述 投票:0回答:1

我正在使用 Springboot 在控制器中返回响应。我在服务类中抛出异常,并在捕获异常时返回特定的响应代码。然而,当我在 Postman 上到达终点时,即使捕获了异常,我仍然会得到

200 ok

这里是服务

public Response signup(RegisterDto register) throws CrossPointException{
        try{
            if (!register.getEmail().matches(EMAIL_PATTERN)){
                throw new CrossPointException("Email is invalid");
            }
            if(!register.getPhoneNumber().matches(PHONE_NUMBER_PATTERN)){
                throw new CrossPointException("Phone number is invalid");
            }
            Optional<User> foundUser = userRepository.findByUsername(register.getEmail());
            if(foundUser.isPresent()){
                throw new CrossPointException("Email already exist");
            }

            User user = new User();
            user.setFirstName(register.getFirstName());
            user.setLastName(register.getLastName());
            user.setPhoneNumber(register.getPhoneNumber());
            user.setEmail(register.getEmail());
            user.setPassword(passwordEncoder.encode(register.getPassword()));
            user.setUsername(register.getEmail());
            user.setCreatedAt(new Date());
            user.setEnabled(false);
            user.setRole(Types.Role.BUSINESS);
            user.setRcNumber(register.getRcNumber());
            user.setUserType(register.getUserType());
            user.setRole(Types.Role.INDIVIDUAL);
            user.setPartnerName(register.getPartnerName());
            user.setBusinessRegistered(register.isBusinessRegistered());
            user.setGender(register.getGender());

            User savedUser = userRepository.save(user);

            basketService.createBasket(savedUser.getId());

            GenerateOtpResponseDto response =  otpService.generateOtp();
            mailService.sendMail(new NotificationEmail("Please Activate your account",
                    user.getEmail(), "this is your verification cade " + response.getOtp()));

            return Response.status(200, "testing this out").entity(BaseResponse.builder().status(true).
                    responseCode(HttpStatus.OK.toString()).message("Thanks for signing up. Kindly check your " +
                    "email to activate your account").data(user).build()).build();
        }catch (CrossPointException ex){

            return Response.status(400, HttpStatus.BAD_REQUEST.toString()).entity(
                    BaseResponse.builder()
                            .responseCode(HttpStatus.BAD_REQUEST.toString())
                            .status(false)
                            .message(ex.getMessage())
                            .build()
            ).build();
        }

    }

这就是我的自定义 BaseResponse 的样子

public class BaseResponse<T> {
    private boolean status;
    private String message;
    private String responseCode;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;
}

当我到达终点时,我得到了一些作为响应的一部分不需要的东西。

{
    "context": {
        "headers": {},
        "configuration": null,
        "entity": {
            "context": {
                "headers": {},
                "configuration": null,
                "entity": {
                    "status": false,
                    "message": "Email already exist",
                    "responseCode": "400 BAD_REQUEST"
                },
                "entityType": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
                "entityAnnotations": [],
                "entityStream": {
                    "committed": false,
                    "closed": false
                },
                "length": -1,
                "language": null,
                "location": null,
                "mediaType": null,
                "committed": false,
                "date": null,
                "lastModified": null,
                "allowedMethods": [],
                "acceptableMediaTypes": [
                    {
                        "type": "*",
                        "subtype": "*",
                        "parameters": {},
                        "quality": 1000,
                        "wildcardType": true,
                        "wildcardSubtype": true
                    }
                ],
                "links": [],
                "entityTag": null,
                "stringHeaders": {},
                "entityClass": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
                "responseCookies": {},
                "acceptableLanguages": [
                    "*"
                ],
                "requestCookies": {},
                "lengthLong": -1
            },
            "status": 400,
            "length": -1,
            "language": null,
            "location": null,
            "mediaType": null,
            "cookies": {},
            "metadata": {},
            "date": null,
            "lastModified": null,
            "allowedMethods": [],
            "entity": {
                "status": false,
                "message": "Email already exist",
                "responseCode": "400 BAD_REQUEST"
            },
            "statusInfo": {
                "reasonPhrase": "400 BAD_REQUEST",
                "statusCode": 400,
                "family": "CLIENT_ERROR"
            },
            "links": [],
            "entityTag": null,
            "stringHeaders": {},
            "headers": {}
        },
        "entityType": "org.glassfish.jersey.message.internal.OutboundJaxrsResponse",
        "entityAnnotations": [],
        "entityStream": {
            "committed": false,
            "closed": false
        },
        "length": -1,
        "language": null,
        "location": null,
        "mediaType": null,
        "committed": false,
        "date": null,
        "lastModified": null,
        "allowedMethods": [],
        "acceptableMediaTypes": [
            {
                "type": "*",
                "subtype": "*",
                "parameters": {},
                "quality": 1000,
                "wildcardType": true,
                "wildcardSubtype": true
            }
        ],
        "links": [],
        "entityTag": null,
        "stringHeaders": {},
        "entityClass": "org.glassfish.jersey.message.internal.OutboundJaxrsResponse",
        "responseCookies": {},
        "acceptableLanguages": [
            "*"
        ],
        "requestCookies": {},
        "lengthLong": -1
    },
    "status": 200,
    "length": -1,
    "language": null,
    "location": null,
    "mediaType": null,
    "cookies": {},
    "metadata": {},
    "date": null,
    "lastModified": null,
    "allowedMethods": [],
    "entity": {
        "context": {
            "headers": {},
            "configuration": null,
            "entity": {
                "status": false,
                "message": "Email already exist",
                "responseCode": "400 BAD_REQUEST"
            },
            "entityType": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
            "entityAnnotations": [],
            "entityStream": {
                "committed": false,
                "closed": false
            },
            "length": -1,
            "language": null,
            "location": null,
            "mediaType": null,
            "committed": false,
            "date": null,
            "lastModified": null,
            "allowedMethods": [],
            "acceptableMediaTypes": [
                {
                    "type": "*",
                    "subtype": "*",
                    "parameters": {},
                    "quality": 1000,
                    "wildcardType": true,
                    "wildcardSubtype": true
                }
            ],
            "links": [],
            "entityTag": null,
            "stringHeaders": {},
            "entityClass": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
            "responseCookies": {},
            "acceptableLanguages": [
                "*"
            ],
            "requestCookies": {},
            "lengthLong": -1
        },
        "status": 400,
        "length": -1,
        "language": null,
        "location": null,
        "mediaType": null,
        "cookies": {},
        "metadata": {},
        "date": null,
        "lastModified": null,
        "allowedMethods": [],
        "entity": {
            "status": false,
            "message": "Email already exist",
            "responseCode": "400 BAD_REQUEST"
        },
        "statusInfo": {
            "reasonPhrase": "400 BAD_REQUEST",
            "statusCode": 400,
            "family": "CLIENT_ERROR"
        },
        "links": [],
        "entityTag": null,
        "stringHeaders": {},
        "headers": {}
    },
    "statusInfo": "OK",
    "links": [],
    "entityTag": null,
    "stringHeaders": {},
    "headers": {}
}

此回复太长并且包含很多无用信息。

我想要的就是这样的:

{
    "status": true,
    "message": "Successfully Joined wait-list",
    "responseCode": "200 OK",
    "data": {
        "id": "6349a3be93a8523e3f40ee00",
        "email": "[email protected]",
        "firstName": "Ojo"
    }
}

这就是我的控制器的样子

  @PostMapping("/signup")
    @PermitAll
    public Response signUp(@RequestBody RegisterDto register) throws CrossPointException{
        return Response.ok(auth.signup(register)).build();
    }
java spring-boot response httpresponse
1个回答
0
投票
@Data
public class BaseResponse<T> {
    private final Boolean status;
    private final String message;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private final LocalDateTime timeStamp;
    private final T payload;

    public BaseResponse(Boolean status, String message, T payload) {
        this.status = status;
        this.message = message;
        this.timeStamp = LocalDateTime.now();
        this.payload = payload;
    }
© www.soinside.com 2019 - 2024. All rights reserved.