【发布时间】:2020-09-05 04:24:06
【问题描述】:
我创建了一个包含所有 crud 操作的 restful Api。当我测试通过 id 获取员工时,我无法显示错误消息。即使我在该 ID 不存在记录时抛出异常。
这是我的控制器代码...
@GetMapping("/employee/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long employeeId) throws ResourceNotFoundException{
Employee employee=service.getEmployeeById(employeeId).orElseThrow(()->new ResourceNotFoundException("Employee not found for this id :"+employeeId));
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
和我的异常类代码
package com.mystyle.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message){
super(message);
}
}
还有我的邮递员错误信息
{
"timestamp": "2020-05-19T06:21:10.172+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/api/v1/employee/2"
}
【问题讨论】:
-
你的异常是否在堆栈跟踪中抛出?
-
您的问题是,您想显示带有适当 HTTP 错误的自定义错误消息吗?如果您使用自定义异常。建议你看看这个帖子:baeldung.com/exception-handling-for-rest-with-spring
标签: java spring-boot exception postman