简体   繁体   English

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

[英]Exception Handler does not catch custom exceptions

I am working at a exception handler and a custom exception class我正在处理异常处理程序和自定义异常 class

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

And

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;
    }
}

When i throw an ApiException in my service class, it should be catched in controller layer but it doesn't work.当我在我的服务 class 中抛出 ApiException 时,它应该在 controller 层中被捕获,但它不起作用。 These are my service and controller functions.这些是我的服务和 controller 功能。

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

And

    @DeleteMapping("/{subjectTypeId}")
public ResponseEntity<Object> deleteSubjectType(@PathVariable int subjectTypeId) {
    subjectTypeService.deleteSubjectType(subjectTypeId);
    return ResponseEntity.ok().body(null);
}

Based on the code provided, I found that it works fine.根据提供的代码,我发现它工作正常。 Make sure that spring can scan the folder where the GeneralExceptionHandler resides确保 spring 可以扫描 GeneralExceptionHandler 所在的文件夹

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

Also add following code to your application.properties还将以下代码添加到您的 application.properties

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM