Spring Boot 异常处理程序不捕获自定义异常

btxsgosb  于 2023-01-13  发布在  Spring
关注(0)|答案(2)|浏览(199)

我正在处理异常处理程序和自定义异常类

@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);
}
wribegjk

wribegjk1#

根据提供的代码,我发现它工作正常,确保Spring可以扫描GeneralExceptionHandler所在的文件夹

s8vozzvw

s8vozzvw2#

@RestControllerAdvice
public class GeneralExceptionHandler {
private static final Logger logger = 
LoggerFactory.getLogger(GeneralExceptionHandler.class);

@ExceptionHandler(Exception.class)
public static ResponseEntity<Object> handleExceptions(Exception e) {
    logger.info("Exception handled:" + e.getMessage() + " with http 
status: " + e.getHttpStatus());
    return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
  }
  }

同时将以下代码添加到application.properties

spring.mvc.throw-exception-if-no-handler-found=true
   spring.resources.add-mappings=false

相关问题