如何在Spring Boot Gateway中添加自定义错误页面?
时间: 2024-12-11 19:30:51 浏览: 26
在Spring Boot Gateway中添加自定义错误页面,你可以通过配置`GlobalErrorController`和`error`路径来实现。以下是步骤:
1. 首先,创建一个实现了`GlobalErrorController`接口的类,例如`CustomErrorController`。这个接口包含一个处理所有未映射HTTP状态码的方法`ServerError`。
```java
import org.springframework.boot.web.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class CustomErrorController {
private final ErrorAttributes errorAttributes;
public CustomErrorController(ErrorAttributes errorAttributes) {
this.errorAttributes = errorAttributes;
}
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> serverError(Exception e) {
// 获取错误信息
Map<String, Object> attributes = errorAttributes.getErrorAttributes(e, true);
// 创建响应体,通常是一个包含错误信息、状态码等的JSON对象
return new ResponseEntity<>(attributes, HttpStatus.valueOf(attributes.getOrDefault("status", HttpStatus.INTERNAL_SERVER_ERROR.value())));
}
}
```
2. 然后,在`application.yml`或`application.properties`文件中配置`server.error.path`,指定错误页面的URL前缀。例如:
```yaml
server:
error:
path: /error
```
现在,当Spring Boot Gateway遇到未处理的异常时,它会将错误信息发送到`/error`路径下的自定义页面。
阅读全文
相关推荐


















