Spring Boot QuickStart 8: Exception handling

Source: Internet
Author: User
Tags object object

Simple example of exception handling:

First step: Create a result entity class

 PackageCom.payease.domain;/*** The outermost object returned by the HTTP request * Created by liuxiaoming on 2017/11/7.*/ Public classResult<t> {    /**Error code*/    PrivateInteger Code; /**Prompt Information*/    PrivateString msg; /**Specific Content*/    PrivateT data;  PublicInteger GetCode () {returnCode; }     Public voidSetcode (Integer code) { This. Code =Code; }     PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }     PublicT GetData () {returndata; }     Public voidsetData (T data) { This. data =data; }}

Step Two: Create the Resultutil tool class

 Packagecom.payease.utils;ImportCom.payease.domain.Result;/*** For results set (Result) tool class * Created by liuxiaoming on 2017/11/7.*/ Public classResultutil { Public Staticresult Success (Object object) {result result=NewResult (); Result.setcode (0); Result.setmsg (Success);        Result.setdata (object); returnresult; }     Public StaticResult Success () {returnSuccessNULL); }     Public Staticresult Error (Integer code,string msg) {result result=NewResult ();        Result.setcode (code);        Result.setmsg (msg); returnresult; }}

Step three: Call in controller

@AutowiredPrivategirlrespository girlrespository; /*** Create a girl*/@PostMapping ("/girls")     PublicResult<girl>Girladd (@Valid Girl Girl, Bindingresult bindingresult) {result result=NewResult (); if(Bindingresult.haserrors ()) {returnResultutil.error (1, Bindingresult.getfielderror (). Getdefaultmessage ());        } girl.setcupsize (Girl.getcupsize ());        Girl.setage (Girl.getage ()); returnresultutil.success (Girlrespository.save (girl)); }

Fourth step: Start the project to submit the request in Postman

Successful request:

Request failed:

Example: Unified exception Handling

First step: Create an enumeration class Resultenum(Unified management error code and error message)

 Packagecom.payease.enums;/*** Created by liuxiaoming on 2017/11/7.*/ Public enumresultenum {unknown_error (-1, "Unknown error"), SUCCESS (0, "Success"), Primary_school (100, "You may still be in primary school."), Middle_school (101, "You may be in junior high."),    ; PrivateInteger Code; PrivateString msg; Resultenum (Integer code, String msg) { This. Code =Code;  This. msg =msg; }     PublicInteger GetCode () {returnCode; }     Public voidSetcode (Integer code) { This. Code =Code; }     PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }}

Step two: Create a Custom exception capture class Exceptionhandle

 PackageCom.payease.handle;ImportCom.payease.domain.Result;ImportCom.payease.enums.ResultEnum;Importcom.payease.exception.GirlException;ImportCom.payease.utils.ResultUtil;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.springframework.web.bind.annotation.ControllerAdvice;ImportOrg.springframework.web.bind.annotation.ExceptionHandler;ImportOrg.springframework.web.bind.annotation.ResponseBody;/*** Custom Exception Capture class * Created by liuxiaoming on 2017/11/7.*/@ControllerAdvice Public classExceptionhandle {//Log    Private Final StaticLogger Logger = Loggerfactory.getlogger (exceptionhandle.class); @ExceptionHandler (Value= Exception.class) @ResponseBody PublicResult handle (Exception e) {if(Einstanceofgirlexception) {girlexception girlexception=(girlexception) e; returnResultutil.error (Girlexception.getcode (), Girlexception.getmessage ()); }Else{logger.info ("" System exception "{}", E); returnResultutil.error (ResultEnum.UNKNOWN_ERROR.getCode (), RESULTENUM.UNKNOWN_ERROR.GETMSG ()); //return Resultutil.error (-1, "Unknown Error:");        }    }}

Step three: Create a custom exception class

 Packagecom.payease.exception;ImportCom.payease.enums.ResultEnum;/*** Custom Exception * Created by liuxiaoming on 2017/11/7.*/ Public classGirlexceptionextendsruntimeexception{PrivateInteger Code;  Publicgirlexception (Resultenum resultenum) {Super(Resultenum.getmsg ());  This. Code =Resultenum.getcode (); }     PublicInteger GetCode () {returnCode; }     Public voidSetcode (Integer code) { This. Code =Code; }}

Fourth step: Add a method to the service

  Public voidGetage (Integer ID)throwsexception{Girl Girl=Girlrespository.findone (ID); Integer Age=Girl.getage (); if(Age < 10){            //back to "you're still in primary school," code=100.            Throw Newgirlexception (Resultenum.primary_school); }Else if(Age > Ten && Age < 16){            //back to "you may be in junior high" code=101            Throw Newgirlexception (Resultenum.middle_school); }        //If >16 years old, add Money//...}

Fifth Step: Call the method in the controller

    /**      * Determine if the age of the girl meets the     requirements by ID @param  ID     @throws  Exception      */     @GetMapping ("Girls/getage/{id}")    publicvoidthrows  exception{         girlservice.getage (ID);    }

Sixth step: Start the project postman submit

Spring Boot QuickStart 8: Exception handling

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.