我想在我的 Spring Boot 应用程序中实现一个处理所有404错误的简单错误控制器。我现在有一个,但它不会发现" /"在初始错误之后。例如:
myapp.localhost / asdflas - 这将由我的控制器
捕获myapp.localhost / asdflas / sadfdsfd - 这将无法正确处理。
我有一个多租户Spring Boot应用程序,因此我需要将变量传递到我的error.html模板以处理自定义属性。目前,对于简单的错误,它工作正常。
我确定以下代码不正确,但我当前的" ErrorHandingController" class看起来像这样:
@Controller
public class ErrorHandlingController implements ErrorController {
@Autowired
private Environment environment;
@Autowired
private ErrorAttributes errorAttributes;
@Autowired
private SaleService saleService;
@Autowired
private OperatorService operatorService;
@Autowired
private AppProperties appProperties;
public void setAppProperties(AppProperties appProperties) {
this.appProperties = appProperties;
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping(value = {"/error/**", "error", "/error"}, produces = "text/html; charset=utf-8")
public String errorGeneric(ModelMap modelMap) {
String tenantName = TenantContext.getCurrentTenant();
String thisURL = environment.getProperty("server.address") + ":" + environment.getProperty("local.server.port");
ReceiptConfig receiptProperties = operatorService.getOperatorProperty();
TenantDTO tenantDTO = operatorService.getOperatorInfo(saleService.getOperatorId(TenantContext.getCurrentTenant()));
if (tenantDTO.getTenantCode() == null)
return "redirect:http://" + thisURL;
modelMap.addAttribute("tenant", tenantDTO);
modelMap.addAttribute("receiptProperties", receiptProperties);
modelMap.addAttribute("url", "http://" + receiptProperties.getUrl() + "." + thisURL);
return "error";
}
}
这种做法有点正确还是我离开了? (我猜测了......)