Spring Boot 实现ErrorController接口处理404、500等错误页面

在项目中我们遇到404找不到的错误、或者500服务器错误都需要配置相应的页面给用户一个友好的提示,而在Spring Boot中我们需要如何设置。

我们需要实现ErrorController接口,重写handleError方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import org.springframework.boot.autoconfigure.web.ErrorController
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping

import javax.servlet.http.HttpServletRequest

@Controller
class MainsiteErrorController implements ErrorController {

@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
//获取statusCode:401,404,500
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code")
if (statusCode == 401) {
return "/401"
} else if(statusCode == 404) {
return "/404"
} else if(statusCode == 403) {
return "/403"
} else {
return "/500"
}
}

@Override
public String getErrorPath() {
return "/error"
}
}

通过上述设置即可实现对应状态码跳转到对应的提示页面。

返回JSON字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import brave.Tracer;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class ErrorHandlerController implements ErrorController {

@Resource
private Tracer tracer;

@Override
public String getErrorPath() {
return null;
}

@RequestMapping("/error")
public Object error() {
RequestContext ctx = RequestContext.getCurrentContext();
ZuulException exception = (ZuulException) ctx.getThrowable();
return ResultBuilder.failure(tracer.currentSpan().context().traceIdString(),
ResponseCode.BAD_REQUEST, "invalid request");
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :