无法使用Controller Advice返回Rest ApiResponse。
已实施解决方案
**我的方法**
1)我创建了一个抛出异常的Controller。
2)Global Exception Handler将使用@ControllerAdvice捕获异常。
3)特定方法将返回响应为APIResponse。
.carousel {
min-height: 480px;
}
.carousel-item {
height: 300px;
width: 300px;
text-decoration: none;
}
img {
height: 300px;
width: 300px;
}
p {
font-size: 1em;
color: red;
text-align: center;
text-decoration: none;
}
System.out.println("此处收到的请求为例外");
{
"timestamp": 1519377824339,
"status": 404,
"error": "Not Found",
"exception": "java.lang.Exception",
"message": "No message available",
"path": "/test"
}
{
"success": false,
"message": "null Your Exception ",
"object": null
}
本地主机:6005 /测试
@RequestMapping("/test")
@RestController
public class TestController {
@Autowired
private UserService userService;
@PostMapping
ApiResponse<User> post(@RequestBody User user) throws Exception {
if(true)
throw new Exception();
return ApiResponse.success().object(userService.post(user));
}
}
@ControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler(value = Exception.class)
public ApiResponse<Void> handleDefaultException(Exception exception) {
System.out.println(" Request Received Here for Exception ");
return ApiResponse.failure().message(exception.getMessage() + "Please check your Response").build();
}
}
public class ApiResponse<T> {
private boolean success;
private String message;
private T object;
public static class ResponseBuilder {
private boolean success;
private String message;
private ResponseBuilder(boolean success) {
this.success = success;
this.message = "";
}
public ResponseBuilder message(String message) {
this.message = message;
return this;
}
public <C> ApiResponse<C> object(C object) {
return new ApiResponse<C>(success, message, object);
}
public <C> ApiResponse<C> build() {
return new ApiResponse<>(success, message, null);
}
}
public static ResponseBuilder success() {
return new ResponseBuilder(true);
}
public static ResponseBuilder failure() {
return new ResponseBuilder(false);
}
private ApiResponse(boolean success, String message, T object) {
this.success = success;
this.message = message;
this.object = object;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
}
}
{
"name":"jalaj"
}
我只能从输出判断我的控制器没有执行。
您可以从我的bitbucket个人资料中下载代码以查看我的代码。
如果我遗失任何东西,有人可以指导我吗?
答案 0 :(得分:0)
从GlobalExceptionHandlerController
TestController
@RequestMapping("/test")
@RestController
public class TestController extends GlobalExceptionHandlerController