Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, 20 December 2012

REST Web Service Spring Error Handling

The Spring framework provides excellent support for building REST web services in a service-oriented architecture (SOA), as I have demonstrated in a previous post, but what is not immediately obvious is how best to deal with errors. Instead of throwing raw exceptions to the client, one would prefer to return a well-formed response consisting of an appropriate HTTP status code and a meaningul response body containing a structured error message in the response form (JSON, XML, ...) requested by the client.

For example, assuming you have a basic REST endpoint such as:

 @RequestMapping(value = "/samples", method = {RequestMethod.GET})
 @ResponseBody
 public SampleList findAllSamples() throws SampleException {
  return new SampleList(service.findAllSamples());
 }

It is good practice in general to not let implementation exceptions leave the service tier, so you might use aspects to catch these and rethrow them as service exceptions.  The code below catches a ReferenceNotFoundException from the data access tier and throws a service exception with the reference number and setting the desired http status code.  Another good practice is to avoid sending free text error messages to a service client, and instead to send structured messages that can be dealt with or rendered as the client sees fit.

@Aspect
@Component("exceptionHandler")
public class ExceptionHandler {

   /**
    * Exception handler for ReferenceNotFoundExceptions
    * 
    * @param nfe the exception being handled
    */
   @AfterThrowing(pointcut = "execution (* com.sample.service.*.*(..))", 
                                              throwing = "nfe")
   public void handleNotFoundException(ReferenceNotFoundException nfe) {
      throw new SampleException(
         new ReferenceNotFoundError(nfe.getReference()), 
                               HttpStatus.NOT_FOUND);
   }


Now to map the service exception (SampleException) to a meaningful HTTP response using the Spring 3 @ExceptionHandler annotation:

   @ExceptionHandler(SampleException.class)
   @ResponseBody
   public SampleErrorList exceptionHandler(SampleException se,
                 HttpServletRequest req,
                 HttpServletResponse res) throws IOException {

      res.setStatus(se.getHttpStatus());

      return new SampleErrorList(se.getErrors());

   }
 

It is also possible to set the HTTP status code using an annotation, but in this example the exception determines this, so the handler sets it programmatically.

See here for a downloadable working sample.

REST Web Service Spring Error Handling
Share:

Wednesday, 17 October 2012

Building a REST Java web service API using the Spring framework

Building a REST-ful Java web service API has never been more restful than now, using version 3+ of the Spring framework.

 First some annotated Java code:

@Component
@Controller()
public class SampleController {

     @Autowired
     private SampleService service;

     @RequestMapping(value = "/samples/{reference}", method = {RequestMethod.GET})
     @ResponseBody
     public Sample getSampleByReference(@PathVariable String reference) {
          return service.getSampleByReference(reference);
      }
 }

Share:

Tuesday, 31 July 2012

REST Web Service API Documentation using RESTdoclet

IG Group has open-sourced RESTdoclet, a maven plugin for generating web-based REST API documentation from REST Java web services implemented using the Spring REST framework.

The plugin:

·         supports Spring 3 REST annotations and JavaDoc out of the box,
·         does not require any additional annotations,
·         is easily integrated with Maven continuous build processes, with minimal configuration,
·         supports multiple streams of service development, and
·         publicises documentation in an interactive, Javadoc-like form, to the web, thus providing a source-code agnostic guide to service consumers.
Share:

Wednesday, 8 October 2008

JBoss

I have in the past worked on Websphere and now Weblogic JEE application servers and fortunately never had to port between the two. Just porting from one version of a product to the next is difficult enough, never mind a cross product port! I have found Weblogic to be a fine product, certainly much easier to learn and use than Websphere, but its not cheap, and one of our prospective clients has raised the question of running on JBoss which is of cours open source.

“No problem!” our sales people cry and I wince. JEE is a fine thing in theory and certainly gives you a hope of porting whereas .NET gives you no such hope at all, but the problem is in those little extras that the vendors give you for competition's sake.

So I worry about those JEE implementation variations, some obvious like the Weblogic deployment specific files, some more subtle, like the way CMP works, and I worry about whether JBoss' messaging and clustering will be as tidy as Weblogic's.

So I've downloaded JBoss and will be giving it a go. Hopefully there are some migration guides and even tools out there to simplify my task, but I'm expecting tears and further hair loss.

What's worse is that I'm dying to get rid of all our EJBs, introduce Spring and Hibernate, and run in a servlet container rather than full a blown application server. That would certainly be much more portable, since with Spring you are essentially taking your application container with you. Of course then you are tied into Spring...
Share:

Saturday, 27 September 2008

Who needs an application server?

If you are primarily building web services then I would give this question serious consideration.

Why spend a fortune on expensive and complex JEE application servers when the combination of Apache Tomcat, Axis webservices (or your favourite open source alternative), Spring AOP container, ACEGI security framework, Hibernate or iBatis persistence frameworks offers a very viable and free alternative?
Share: