0

在使用 Java 1.8、lombok 和 Spring Boot 2.1.5.RELEASE 的项目中,创建了一个自定义异常,该异常未显示在我的日志文件或标准输出中的任何位置。


pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
   <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <optional>true</optional>
   </dependency>
</dependencies>

休息控制器:

@Slf4j
@RestController
@RequestMapping("/products")
public class RestController {

    private HttpHeaders headers = null;

    @Autowired
    ProductDao productDao;

    public RestController() {
        headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
    }

    @RequestMapping(value = {"/{id}"}, 
                    method = RequestMethod.GET, 
                    produces = "APPLICATION/JSON")
    public ResponseEntity<Object> getProductByUsingId(@PathVariable(value = "id", required = true) Integer id) 
    throws IOException, ProductNotFoundException {

        if (null == id) {
            return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
        }

        ProductResponse product = productDao.findProductById(id);

        if (null == product) {
            return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<Object>(product, headers, HttpStatus.OK);
    }
}

产品未找到异常:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Product Not Found")
public class ProductNotFoundException extends Exception {

    private static final long serialVersionId = 1L;

    public ProductNotFoundException(int id) {
        super("Product does not exist with id: " + id);
    }
}

控制器建议:

@Slf4j
@ControllerAdvice(annotations = RestController.class)
public class ProductControllerAdvice {

    @ExceptionHandler(ProductNotFoundException.class)
    @ResponseStatus(value= HttpStatus.NOT_FOUND)
    public void handleProductNotFoundException() {
        log.error("\n\n\tProductNotFoundException handler executed\n");
    }
}

当我点击我的 REST 端点时:

http://localhost:8080/products/0

它返回一个 HTTP 404 - 它应该。

grep -rnw logs.log -e 'ERROR'但是我在我的logs.log(使用)文件和/或标准输出中的任何地方都没有看到错误?

另外,试过了ProductNotException extend RuntimeException,还是不行。。。

我可能做错了什么?

4

0 回答 0