【问题标题】:Sprint boot custom exception not getting caught and response is always empty if error with status 200如果状态为 200 的错误未捕获 Spring Boot 自定义异常并且响应始终为空
【发布时间】:2021-09-11 23:00:22
【问题描述】:

我在spring-boot 自定义异常处理方面遇到了很多困难。客户异常没有被异常处理程序捕获。 REST API 适用于有效的请求负载。当出现错误时,我正在尝试发送错误响应。但错误响应始终为空,状态码为 200 而不是 404。

Controller

package com.company.paypage.v2.controller;

import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.company.paypage.exception.*;
import com.company.paypage.model.ErrorMessageConstants;
import com.company.paypage.v2.model.ConfigPayload;
import com.company.paypage.v2.model.ConfigResponse;
import com.company.paypage.v2.services.FeatureConfigService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping(value = "v2/setup")
public class FeatureConfigController {
    
     @Autowired
     private FeatureConfigService featureconfigService;

     /*
        features config endpoint
     */
     @RequestMapping(value = "/config", method = POST, consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
     public ConfigResponse setupConfigRequest(@Valid @RequestBody ConfigPayload payload, HttpServletRequest request, HttpServletResponse servResponse) {
        log.info("Processing the feature config request for " + payload.getPage_type());
        ConfigResponse response = null;
        try {
            response = featureconfigService.processConfigRequest(payload);
            System.out.println(response);
            if(response == null) {
                throw new FeatureConfigException(ErrorMessageConstants.NOT_FOUND, "Error while generating feature config response.....");
            }
        } catch (FeatureConfigException e){
            log.error("Exception:",  e);
        }
        return response;
    } 
}

Exception class

package com.company.paypage.exception;

public class FeatureConfigException extends Exception {
    String code;
    String message;

    public FeatureConfigException(String code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Exception handler

package com.company.paypage.exception;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.company.paypage.model.ApplicationConstants;
import com.company.paypage.model.ErrorCodeConstants;
import com.company.paypage.model.ErrorMessageConstants;
import com.company.paypage.model.GeneralErrorInfo;
import com.company.paypage.model.Payment;
import com.company.paypage.model.SetupResponse;
import com.company.paypage.v2.model.ConfigResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
public class GeneralExceptionHandler{

    @ExceptionHandler(FeatureConfigException.class)
    protected ResponseEntity<ConfigResponse> handleFeatureConfigException(FeatureConfigException ex, HttpServletRequest request){

        GeneralErrorInfo generalErrorInfo = new GeneralErrorInfo().withCode(ex.getCode());
        generalErrorInfo.setMessage(ex.getMessage());
        String referenceId =(String) request.getAttribute(ApplicationConstants.REFERENCE_ID);
        ConfigResponse configResponse = buildConfigResponse(generalErrorInfo, referenceId);

        log.error("{} {}-{}"
                , ex.getMessage()
                , request.getHeader(ApplicationConstants.X_GP_REQUEST_ID)
                , referenceId
                , ex);  
        
        return new ResponseEntity<ConfigResponse>(configResponse, addCustomerHeaders(request), HttpStatus.BAD_REQUEST);

    }
    
    @SuppressWarnings("null")
    ConfigResponse buildConfigResponse(GeneralErrorInfo generalErrorInfo, String referenceId) {

        ConfigResponse configResponse = new ConfigResponse();
        configResponse.setError(generalErrorInfo);
        configResponse.setAutocomplete((Boolean) null);
        configResponse.setRefund((Boolean) null);
        configResponse.setSplit_payment((Boolean) null);
        configResponse.setTender_type(null);
        configResponse.setVoidd((Boolean) null);
        return configResponse;
    }

}

ConfigResponse model

package com.company.paypage.v2.model;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.company.paypage.model.GeneralErrorInfo;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "tender_type",
    "autocomplete",
    "split_payment",
    "refund",
    "void",
    "error"
})

public class ConfigResponse implements Serializable {
    
    @JsonProperty("tender_type")
    private TenderType tender_type;
    
    @JsonProperty("autocomplete")
    private boolean autocomplete;
    
    @JsonProperty("split_payment")
    private boolean split_payment;
    
    @JsonProperty("refund")
    private boolean refund;
    
    @JsonProperty("void")
    private boolean voidd;
    
    @JsonProperty("error")
    private GeneralErrorInfo error;

    public TenderType getTender_type() {
        return tender_type;
    }

    public void setTender_type(TenderType tender_type) {
        this.tender_type = tender_type;
    }

    public boolean isAutocomplete() {
        return autocomplete;
    }

    public void setAutocomplete(boolean autocomplete) {
        this.autocomplete = autocomplete;
    }

    public boolean isSplit_payment() {
        return split_payment;
    }

    public void setSplit_payment(boolean split_payment) {
        this.split_payment = split_payment;
    }

    public boolean isRefund() {
        return refund;
    }

    public void setRefund(boolean refund) {
        this.refund = refund;
    }

    public boolean isVoidd() {
        return voidd;
    }

    public void setVoidd(boolean voidd) {
        this.voidd = voidd;
    }
    
    public GeneralErrorInfo getError() {
        return error;
    }

    public void setError(GeneralErrorInfo error) {
        this.error = error;
    }

    public ConfigResponse withError(GeneralErrorInfo error) {
        setError(error);
        return this;
    }
}

这可能是什么问题?为了得到JSON 格式的正确错误响应,我错过了什么?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    您必须定义异常的代码。在这里您可以找到如何处理 REST 异常的不同变体:link

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多