在 SpringBoot 中默认的 404 返回的信息如下:
我们如果要对 404 返回的异常信息做重新定义,我们需要新建一个 controller 来处理它,如下:
import com.asurplus.common.utils.RES;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NotFoundController implements ErrorController {
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping("/error")
public RES error(HttpServletResponse response) {
// 返回正确状态码
response.setStatus(HttpStatus.SC_OK);
// 返回异常信息
return RES.no(404, "Not Found Exception");
}
}
实现了 ErrorController 接口,SpringBoot 发生 404 后会重定向到 /error 页面,所以我们定义访问 /error 路径,返回一个 JSON 对象,返回的信息如下:
返回的信息就是我们自定义的了
如您在阅读中发现不足,欢迎留言!!!



