【发布时间】:2021-10-08 18:28:18
【问题描述】:
我已经写了特定的异常,但我的 GlobalExceptionHandler 不起作用,任何帮助将不胜感激。谢谢。
下面是我的 GlobalException 类;
@ControllerAdvice
public class GlobalExceptionHandler {
public static final String EXCEPTION_OCCURED_LOG_PREFIX = "Exception occured: {}";
public static final String EXCEPTION_OCCURED_LOG_DETAIL = "Exception log detail occured: {}, class: {}";
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler({BadRequestException.class})
public ResponseEntity<BaseResponse> handleBadRequest(BadRequestException ex) {
String logSuffix = Arrays.toString(ex.getStackTrace());
logger.error(EXCEPTION_OCCURED_LOG_PREFIX, logSuffix);
logger.error(EXCEPTION_OCCURED_LOG_DETAIL, ex.getMessage(), ex.getClass());
BaseResponse response = new BaseResponse();
response.setCode(Constants.B_BADREQUEST);
response.setMessage("BadRequestException occured! Exception details: ".concat(ex.getMessage()));
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(response);
}
下面是我的 BaseResponse 类;
public class BaseResponse {
private String code;
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
下面是我的请求模型类;
@Entity
@Data
public class SchoolRequest {
@Id
@NotNull
@JsonProperty("school")
private String school;
调用下面的异常类;
private void schoolRule(SchoolRequest schoolRequest) {
if (schoolRequest.getSchool() == null || schoolRequest.getSchool().isEmpty()) {
throw new BadRequestException("School can not be null or empty");
}
}
下面是我的 BadRequestException 类;
public class BadRequestException extends RuntimeException{
public BadRequestException(String message) {
super(message);
}
}
下面是我的控制器类;
public class SchoolController {
private final School schoolService;
@PostMapping(ApiPaths.schoolController.CTRL)
public ResponseEntity<SchoolResponse> createSchool(@Valid @RequestBody SchoolRequest request) throws Exception {
return schoolService.createSchool(request);
}
}
我在下面收到的错误代码;
"code": "INTERNAL_SERVER_ERROR",
"message": "Internal Server Error occured! Exception details: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<eu.demo.school.model.SchoolResponse> eu.demo.school.controller.SchoolController.createSchool java.lang.Exception: [Field error in object 'schoolRequest' on field 'school': rejected value [null]; codes [NotNull.schoolRequest.prefix,NotNull.prefix,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [schoolRequest.prefix,prefix]; arguments []; default message [school]]; default message [must not be null]]
【问题讨论】:
-
您能否包括您的 SchoolService 课程和您收到的异常?
标签: java spring-mvc exception