1

I would like to implement a simple error controller within my Spring Boot app that handles all 404 errors. I currently have one now, however it won't catch any errors with a "/" after the initial error. So for example:

myapp.localhost/asdflas - this will be caught by my controller

myapp.localhost/asdflas/sadfdsfd - this will not be handled correctly.

I have a multi-tenant Spring Boot app, so I need to pass in variables to my error.html template in order to process custom properties. Currently, for the simple errors it is working fine.

I'm sure the following code I have is not correct, but my current "ErrorHandingController" class looks like this:

@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";

}

}

Is this approach somewhat correct or am I way off? (I'm guessing way off..)

SiriusBits
  • 760
  • 2
  • 10
  • 26
  • Possible duplicate of http://stackoverflow.com/questions/38777723/how-i-create-an-error-handler-404-500-in-spring-boot-mvc?rq=1 – Ivan Pronin Apr 07 '17 at 19:48

0 Answers0