我正在处理异常处理程序和自定义异常类
@ControllerAdvice
public class GeneralExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GeneralExceptionHandler.class);
@ExceptionHandler(ApiException.class)
public static ResponseEntity<Object> handleExceptions(ApiException e) {
logger.info("Exception handled:" + e.getMessage() + " with http status: " + e.getHttpStatus());
return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
}
}
还有
public class ApiException extends Exception{
private final String message;
private final HttpStatus httpStatus;
public ApiException(String message, HttpStatus httpStatus) {
this.message = message;
this.httpStatus = httpStatus;
}
@Override
public String getMessage() {
return message;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
当我在我的服务类中抛出ApiException时,它应该在控制器层中被捕获,但它不起作用。
@Override
public Boolean deleteSubjectType(int subjectTypeId) throws ApiException {
SubjectType subjectType=subjectTypeRepository.findById(subjectTypeId)
.orElseThrow(()->new ApiException("Subject Type Id not found", HttpStatus.NOT_FOUND));
return true;
}
还有
@DeleteMapping("/{subjectTypeId}")
public ResponseEntity<Object> deleteSubjectType(@PathVariable int subjectTypeId) {
subjectTypeService.deleteSubjectType(subjectTypeId);
return ResponseEntity.ok().body(null);
}
2条答案
按热度按时间wribegjk1#
根据提供的代码,我发现它工作正常,确保Spring可以扫描GeneralExceptionHandler所在的文件夹
s8vozzvw2#
同时将以下代码添加到application.properties