springboot访问不存在的URL时的处理方法
在前后端分离的模式下,当Spring Boot应用接收到一个不存在的URL请求时,通常希望返回一个固定的JSON字符串作为响应,以便前端能够据此进行相应的处理。
最初的思路是自定义一个错误控制器来处理404错误,并返回一个JSON格式的响应体。让错误控制器实现ErrorController接口,并重写getErrorPath()方法以指定错误处理的路径。然后,你可以在这个控制器中创建一个处理404错误的方法。
然而却发现springboot3.3.5中ErrorController没有任何接口方法,只能另辟蹊径,考虑使用ErrorPageRegistrar。
ErrorPageRegistrar
ErrorPageRegistrar是Spring Boot中用于注册错误页面的接口。通过实现这个接口,可以自定义不同HTTP状态码对应的错误页面。
ErrorPageRegistrar接口定义在Spring Boot的Web模块中,它包含一个方法registerErrorPages(ErrorPageRegistry registry)。这个方法用于注册错误页面,其中ErrorPageRegistry是一个用于添加错误页面的注册表。
实现接口
创建一个类实现ErrorPageRegistrar接口,并重写registerErrorPages方法。在这个方法中,可以使用ErrorPageRegistry的addErrorPages方法来添加多个错误页面。
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
/**
* @基本功能:
* @program:ecconfigcenter
* @author:Jet
* @create:2024-11-07 17:29:58
**/
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
// 注册404错误页面
ErrorPage error404 = new ErrorPage(HttpStatus.NOT_FOUND, "/ec/error/404");
// 注册500错误页面
ErrorPage error500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/ec/error/500");
// 将错误页面添加到注册表中
registry.addErrorPages(error404, error500);
}
}
这里使用@Configuration注解标记ErrorPageConfig为配置类,以便Spring Boot能够自动扫描并注册这个配置。
在registerErrorPages方法中,通过创建ErrorPage对象来指定HTTP状态码和对应的错误处理的路径。然后,将这些ErrorPage对象传递给addErrorPages方法。
注册错误处理
import cn.com.ec.eccommon.common.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* @基本功能:
* @program:ecconfigcenter
* @author:Jet
* @create:2024-11-07 17:29:58
**/
@Slf4j
@RequestMapping("/ec")
@Controller
public class CustomErrorController extends BaseController {
/**
* 404处理
* @return
*/
@RequestMapping(value = "/error/404",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> handle404() {
Map<String,Object>result = new HashMap<>();
result = this.setJson(404,"url is invalid.",null);
return result;
}
/**
* 500处理
* @return
*/
@RequestMapping(value = "/error/500",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> handle500() {
Map<String,Object>result = new HashMap<>();
result = this.setJson(500,"Server internal error.",null);
return result;
}
}