This is the 23rd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Unified processing returns the result
This is mainly implemented using @ControllerAdvice and @ExceptionHandler annotations of SpringMvc. @controlleradvice declares a ControllerAdvice. @exceptionhandler annotates the method to intercept the exception indicated on the value property.
When the background in the development process, often need to return a JSON object to the front-end. When an exception occurs, we also hope to return the exception in JSON format, so that the front-end can display the status code and information of the returned JSON data accordingly.
In this case, you need to write an Http outermost wrapper object, unified return object data. Result.java
public class Result<T> { private Integer code; private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; }}Copy the code
Based on the returned data object, the corresponding result template utility class, resultutil.java, can be wrapped
public class ResultUtil { public static Result getOK(Object object){ Result result = new Result(); result.setCode(0); Result. SetMsg (" success "); result.setData(object); return result; } public static Result getOK(){ return getOK(null); } public static Result getError(Integer code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; }}Copy the code
When the background judges the data transmitted from the front end and returns the corresponding results, unified exception processing can be carried out. Throwing the result, if thrown directly, is not in the JSON format we returned earlier, which is not friendly. We can capture the exception and call the resulting template class (resultutil.java) to return our wrapped JSON data.
ExceptionHandler. Java
import com.demo.result.Result; import com.demo.result.ResultUtil; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class ExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public Result handle(Exception e){ return ResultUtil.getError(100,e.getMessage()); }}Copy the code
If you just throw the result with default Exception and return the same status code every time, it will be difficult for the front end to handle. This requires a custom Exception. Note that exceptions cannot be inherited because springBoot only supports inheriting runtimeExceptions.
Custom Exception class userException.java
public class UserException extends RuntimeException { private Integer code; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public UserException(Integer code,String message) { super(message); this.code = code; }}Copy the code
The exception catching class ExceptionHandler.java also needs to be changed at this point
import com.demo.exception.UserException; import com.demo.result.Result; import com.demo.result.ResultUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @controllerAdvice public Class ExceptionHandler {// Add exception log printing private Final Static Logger Logger = LoggerFactory .getLogger(ExceptionHandle.class); @ExceptionHandler(Exception.class) @ResponseBody public Result handle(Exception e){ if(e instanceof UserException){ UserException userException = (UserException)e; return ResultUtil.getError(userException.getCode() ,userException.getMessage()); }else{logger.error(" [system exception] ={}",e); Return resultutil. getError(-1," Unknown error!" ); }}}Copy the code
Through the unified processing of the results, it can be very friendly to return the data to the front end, but at the moment, I found a problem, is that each time the data is returned, the status code and information have to be redefined in the call method, so that the state is a little more, it is difficult to view and modify. To do this, you can define an enumerated class that manages code and MSG uniformly.
ResultEnum.java
Public enum ResultEnum {/** * Succeeded. ErrorCode: 0 */ SUCCESS("0"," SUCCESS "), /** * Unknown exception. ErrorCode: 01 */ UnknownException("01"," UnknownException "), /** * System exception. ErrorCode: 02 */ SystemException("02"," SystemException "), /** * service error. ErrorCode: 03 */ MyException("03"," service error "), /** * Error level. ErrorCode: 04 */ InfoException("04", "warning level error "), /** * Database operation exception. ErrorCode: 020001 */ DBException("020001"," database operation exception "), /** * Parameter verification error. ErrorCode: 040001 */ ParamException("040001"," Parameter verification error "); private String code; private String msg; ResultEnum(String code, String msg) { this.code = code; this.msg = msg; } public String getCode() { return code; } public String getMsg() { return msg; }}Copy the code