【问题标题】:How to customize the internal server error message (error code : 500)如何自定义内部服务器错误信息(错误代码:500)
【发布时间】:2023-03-29 19:54:01
【问题描述】:

考虑一个场景,我想用现有的 ID 在数据库中创建一条记录。通过这样做,我们得到“500-internal server error”。但我想自定义返回“Id 已存在,无法创建记录”的消息。以下是我的示例现有代码: 控制器类:

    @PostMapping(value = "/plans")
    public ResponseEntity<ResponseSave> savePostPlanDetails(
            @Valid @RequestBody(required = true) Plan plan) throws ParseException {

        String planId = plan.getPlanId();

        Integer createdId = planDataService.savePlan(plan, planId);

        ServiceMessage serviceMessage = ServiceMessage.createCreatedServiceMessage();
        return new ResponseEntity<>(ResponseSave.createResponseSave(serviceMessage, createdId), HttpStatus.CREATED);
    }

服务等级:

public Integer savePlan(Plan plan, String planId) throws ParseException {


        PlanDao findResponse = planDataRepository.findByPlanId(planId);

        if (findResponse != null) {
            //This line generate 500 error if create with already existing ID.
            throw new IllegalArgumentException(PlanSearchEnum.RECORD_ALREADY_EXIST.getValue());                                                                                                 
        }
        
        PlanDao planDao1 = requestToResponseMapper.panToPlanDao(plan);
        PlanDao saveResponse = planDataRepository.save(planDao1);
        return saveResponse.getInternalId();

    }

邮递员输出:

{
    "message": {
        "code": "500",
        "description": "Unable to process request",
        "type": "Internal Server Error"
    }
}

在上面的邮递员回复中,我希望描述类似于:“描述”:“Id 已经存在,无法创建记录”,而不是如上所示的一般消息。那么如何做到这一点呢?

【问题讨论】:

    标签: java json spring-boot rest postman


    【解决方案1】:

    您需要有一个异常处理程序:

    @ControllerAdvice
    @Slf4j
    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
        @ExceptionHandler(value = {IllegalArgumentException.class})
        public ResponseEntity<Object> handleIllegalArgumentExceptions(Exception exception, WebRequest webRequest) {
            HttpStatus errorCode = HttpStatus.INTERNAL_SERVER_ERROR;
    
            return this.handleExceptionInternal(exception, new ErrorInfo(errorCode.value(), "Id already exist, Cannot create record"), new HttpHeaders(), errorCode, webRequest);
        }
    }
    

    还有模特ErrorInfo

    public class ErrorInfo {
        private final int code;
        private final String description;
    }
    

    最后,您绝对应该考虑创建自己的异常,而不是使用通用的IllegalArgumentException。您可以为您的业务案例创建更有意义的内容,例如 RecordAlreadyExistsException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-03
      • 2020-08-23
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多