正在开发一个 spring-boot 项目,并尝试在邮递员正文中发送一个自定义错误,如下所示。
{
status:404,
message:"No Question Found."
}
在我的服务类我已经实现了这段代码,我想发送错误。
if (outputDTOSet.size() != 0) {
} else {
throw new BusinessException(Response.Status.NOT_FOUND,"No Question Found");
}
但是在控制台中出现错误。
[Request processing failed: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl] with root cause
BusinessException类
public class BusinessException extends WebApplicationException {
public BusinessException(Response.Status status, String errorMessage){
super(Response.status(status)
.entity(new ErrorResponse(status.getStatusCode(), errorMessage)).type(MediaType.APPLICATION_JSON).build());
}
}
ErrorResponse.java类
@Data
@AllArgsConstructor
public class ErrorResponse {
private int status;
private String errorMessage;
}
请帮忙。
您的代码中有很多错误。 springboot中捕获自定义异常应该按如下方式完成:
创建自定义异常:
@Getter
@Setter
@AllArgsConstructor
public class BusinessException extends RuntimeException { // I didn't find the WebApplicationException , so I replaced it with RuntimeException
private int status;
private String message;
}
捕获自定义异常并返回错误消息
@ControllerAdvice // This annotation must be added
@Slf4j
public class BusinessExceptionHandler {
@ExceptionHandler(BusinessException.class) // This annotation must be added
@ResponseBody
public ErrorResponse handleBusinessException(BusinessException e) {
log.error("BusinessException: {}", e.getMessage());
return new ErrorResponse(e.getStatus(), e.getMessage());
}
}
测试
@RequestMapping("/error_test")
public void error() {
throw new BusinessException(404, "No Question Found");
}