在一个使用java1.8、lombok和springboot2.1.5.release的项目中,创建了一个自定义异常,它不会出现在我的日志文件或stdout中的任何地方。
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>
REST控制器:
@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);
}
}
productnotfoundexception:
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");
}
}
当我到达休息终点时:
http://localhost:8080/products/0
它返回一个HTTP404—它应该返回。
但是在我的logs.log(使用 grep -rnw logs.log -e 'ERROR'
)文件和/或内部标准输出?
还有,我试过 ProductNotException extend RuntimeException
,但还是没用。。。
我可能做错了什么?
暂无答案!
目前还没有任何答案,快来回答吧!