SPRINGMVC Learning note exception handling for--rest API

Source: Internet
Author: User

Objective:
Recently, using SPRINGMVC to write a lot of rest API, feel really a good framework. Some of the previous articles on rest APIs are still not perfect. For example, when the parameter is missing, the type mismatch situation, directly throws an exception, the content returned is the wrong page of the researcher, rather than JSON content, which makes the mobile side of the caller difficult to handle.
This article mainly deals with the solution of SPRINGMVC to exceptions for rest API.

Series Finishing:
SPRINGMVC The article Directory of the Learning Notes series:
idea creating a SPRINGMVC project
• Mobile-oriented rest API
Use and customization of Jackson
Design principles for REST API blog post
• Mobile Internet combat-web Restful API design and infrastructure

Scene Construction:
Background, we have used the Jackson Framework and annotated @resonsebody to implement the Pojo object in JSON form.
First, we will construct several cases to describe the problems we are going to solve.
Common Test Code:

@Controller @requestmapping ("/math") public class TestController {    @RequestMapping (value= "/div", method= Requestmethod.get)    @ResponseBody public    int Div (@RequestParam ("a") int A,                    @RequestParam ("b") int b) {        //*) div zero error        return a/b;    }}

1). Scene One (parameter missing, type mismatch)
Case 1:
http://localhost:8080/math/div?a=10
Parameter b missing, 400 error page returned
  
Case 2:
Http://localhost:8080/math/div?a=10&b=hehe
Wrong type of parameter B, type conversion failed
  
Our hope is that the exceptions to the missing/type mismatch of these parameters will be returned as a JSON string instead of a 400 error page.
2). Scenario Two (business code throws an exception)
Case 1:
Http://localhost:8080/math/div/a=10&b=0
Exception occurred except 0
  
It's very common to throw business exceptions inside, and it's not easy to go back to the wrong page.

Solution:
Based on the above scenario, when an exception is encountered, the 400+/500+ error page is returned, on the one hand, the Client SDK resolves and handles the trouble, on the other hand leaks the internal error details. Is there a way to intercept the exception and return the error data format that you defined?
The answer is yes, SPRINGMVC introduced the weaving @ControlAdvice.
Its handling of the exception is very convenient, can be simply referred to the following sample.

@ControllerAdvicepublic class Restapicontroladvice {@ExceptionHandler (Value=runtimeexception.class) @ Responsebodypublic String handle (runtimeexception e) {//* Enter the Exception Log return e.getmessage ();} @ExceptionHandler (value=exception.class) @ResponseBodypublic String handle (Exception e) {//* logged in Exception Log return E.getmessage ();}}

By combining the annotation @ExceptionHanlder, you define the specific exception handling and the returned results.
It is important to note that @ExceptionHandler can define multiple, and when more than one match, the earliest processing function is first processed. This side is like the common case of Try/catch, which is both order-sensitive. Best practice, you need to shelve the top-level exception class to the end of the code.
Of course, for the parameter missing/Type mismatch processing, you can define as follows.

@ExceptionHandler (value=missingservletrequestparameterexception.class) @ResponseBodypublic tresult<void> Handle (Missingservletrequestparameterexception e) {return "Miss parameter" + e.getparametername () + ":" + e.getparameter Type ();} @ExceptionHandler (value= typemismatchexception.class) @ResponseBodypublic String handle (typemismatchexception e) { return E.geterrorcode () + ", Required type:" + e.getrequiredtype () + ", but value:" + E.getvalue ();}

The exception code in the business can often be abstracted out of an exception base class.

Summarize:
Springmvc is really quick to get started and getting started, but to really understand. Really still need to spend Kung fu, this is just a brief introduction, and did not go into the source code. I hope one day I will have the opportunity to talk about the technical principles behind.

Public Number & Games sites:
Personal public Number: Wooden purpose H5 game world
  
For a personal game folio site, please click to visit : http://120.26.221.54/.

SPRINGMVC Learning note exception handling for--rest API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.