lundi 23 février 2015

Throw exception from spring controller which producces xml MediaType

I have the the following controller with one RequestMapping which produces an xml MediaType.



@RestController
@RequestMapping("/api")
public class ArticleResource {

@RequestMapping(value = "/xml/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<byte[]> getXml(@PathVariable(value = "id") String id,
final HttpServletRequest request,
final HttpServletResponse response) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path + id + ".xml");

} catch (FileNotFoundException e) {
throw new BadRequestException("No such xml exists");
}
try {
return new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream), HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
}
}


The BadRequestException implementation is the following:



@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {

public BadRequestException(String message) {
super(message);
}

}


It works fine when the xml exists, but when the xml cannot be found I have a 406 error code. I suppose the problem occurs because it expects a xml media type and instead a RuntimeException is returned. How can I tackle with this issue?


Aucun commentaire:

Enregistrer un commentaire