Close

Spring Boot - Returning XML error response from Custom ErrorController

Following example shows how to return XML error response from our custom ErrorController.

Example

Our Custom ErrorController

@Controller
public class MyCustomErrorController extends AbstractErrorController {

    public MyCustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping(value = "/error", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public Error handleError(HttpServletRequest request) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(request, true);

        List<Attribute> attributes = new ArrayList<>();
        errorAttributes.forEach((key, value) -> {
            Attribute attribute = new Attribute();
            attribute.setKey(key);
            attribute.setValue(value == null ? "" : value.toString());
            attributes.add(attribute);
        });
        Error error = new Error();
        error.setAttributeList(attributes);
        return error;
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Error {
    @XmlElement(name="attribute")
    private List<Attribute> attributeList;
    .............
}
@XmlRootElement
public class Attribute {
    private String key;
    private String value;
    .............
}

An application Controller

@Controller
public class MyAppController {

    @RequestMapping("/")
    public void handleRequest() {
        throw new RuntimeException("test exception");
    }
}

Boot main class

@SpringBootApplication
public class SpringBootMain{

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class);
    }
}

Output

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.0.0.RELEASE
    Corresponding Spring Version 5.0.4.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

boot-produce-error-in-xml Select All Download
  • boot-produce-error-in-xml
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyCustomErrorController.java

    See Also