<>1. exception handling

<>1). Define enumeration class , Manage exception classification
import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import java.
util.LinkedHashMap; @NoArgsConstructor @AllArgsConstructor public enum
ResponseCode{ /*-----Basic-----*/ SUCCESS(200," Operation successful "), FAIL(500," operation failed "),
/*-----User (StartCode: 1000)-----*/ USER_PASSWORD_ERROR(1000," Password error "),
USER_NOT_FOUND(1001," user does not exist "); public Integer code; public String msg; public
static LinkedHashMap<Integer,String> getArrayMessage(){ LinkedHashMap<Integer,
String> responseMessages = new LinkedHashMap<>(); for (ResponseCode statusEnum :
ResponseCode.values()) { responseMessages.put(statusEnum.code,statusEnum.msg);
} return responseMessages; } }
This enumeration class is more important , We'll use it later .

<>2). Write custom exception
import lombok.*; import com.xxx.xxx.response.ResponseCode; import java.io.
Serializable; @EqualsAndHashCode(callSuper = true) @Data @Builder
@AllArgsConstructor // If it appears at compile time “java: Already in class top.yuanmen.oa, //
.exception.RequestException Constructor defined in // RequestException()” Delete this note
//@NoArgsConstructor public class RequestException extends RuntimeException
implements Serializable { private Integer code; private String msg; private
Exception e; public RequestException(ResponseCode responseCode, Exception e) {
this.code = responseCode.code; this.msg = responseCode.msg; this.e = e; } public
RequestException(ResponseCode responseCode) { this.code = responseCode.code;
this.msg = responseCode.msg; } public synchronized static RequestException fail(
String msg){ return RequestException.builder().code(ResponseCode.FAIL.code).msg(
msg).build(); } public synchronized static RequestException fail(String msg,
Exception e){ return RequestException.builder().code(ResponseCode.FAIL.code).msg
(msg).e(e).build(); } public synchronized static RequestException fail(Integer
code,String msg,Exception e){ return RequestException.builder().code(code).msg(
msg).e(e).build(); } }
<>3). use
@Override public void addUser(User user) { try { boolean res = this.insert(user
); if (!res) throw new RequestException(ResponseCode.FAIL); } catch (Exception e
){ throw new RequestException(ResponseCode.FAIL); } }
My method here is to add a user information , My user's phone It's a rule 11 position , Use this to make an exception :
@Test public void userServiceTest() { User user = User.builder().loginId(
"875044497").username("admin").password("123456") .gender(1).phone(
"13980449849000").email("8750444497").department_id("1032513234847997954").build
(); userService.addUser(user); }
<>4. Global exception handling

Global exception handling is mainly used to deal with the scope that our custom exception does not take into account . The global exception here is mainly for controller Stratified .
Using annotations @ControllerAdvice Mark a class as a global exception handling class :
import com.xxx.xxx.exception.RequestException; import com.xxx.xxx.response.
ResponseCode; import com.xxx.xxx.response.ResponseResult; import lombok.extern.
log4j.Log4j; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult; import org.springframework.
validation.ObjectError; import org.springframework.web.bind.
MethodArgumentNotValidException; import org.springframework.web.bind.annotation.
ControllerAdvice; import org.springframework.web.bind.annotation.
ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List; @ControllerAdvice(basePackages = {
"com.xxx.xxx.controller"}) @Log4j public class GlobalDefaultExceptionHandler {
// Request exception @ExceptionHandler(value = RequestException.class) @ResponseBody public
ResponseResultrequestExceptionHandler(RequestException e){ if(e.getE()!=null) e.
printStackTrace(); return ResponseResult.builder().msg(e.getMsg()).code(e.
getCode()).build(); } // Parameter validation exception @ExceptionHandler(value =
DataIntegrityViolationException.class) @ResponseBody public ResponseResult
requestExceptionHandler(DataIntegrityViolationException e){ return
ResponseResult.builder().msg(ResponseCode.SYSTEM_DATA_FAIL.msg).code(
ResponseCode.FAIL.code).build(); } @ExceptionHandler(
MethodArgumentNotValidException.class) @ResponseBody public ResponseResult
methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
BindingResult result= e.getBindingResult(); String s = " Parameter validation failed "; if(result.
hasErrors()){ List<ObjectError> errors = result.getAllErrors(); s = errors.get(0
).getDefaultMessage(); } return ResponseResult.builder().code(ResponseCode.
SYSTEM_PARAM_FAIL.code).msg(s).build(); } // All exceptions @ExceptionHandler(value =
Exception.class) @ResponseBody public ResponseResult requestExceptionHandler(
Exception e){ e.printStackTrace(); return ResponseResult.builder().msg(
" There is a small problem in the system , Repairing ~").code(ResponseCode.FAIL.code).build(); } }
<>2. Unified response data body structure

<>1). Write unified result response body
import io.swagger.annotations.ApiModel; import io.swagger.annotations.
ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder;
import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable
; @Data @NoArgsConstructor @AllArgsConstructor @Builder @ApiModel(value =
" Request result response body ") public class ResponseResult<T> implements Serializable {
@ApiModelProperty(" Error code ") private Integer code; @ApiModelProperty(" Data body ") private
T data; @ApiModelProperty(" news ") private String msg; @ApiModelProperty(" Response time stamp ")
private final long timestamps = System.currentTimeMillis(); public synchronized
static <T> ResponseResult<T> build(ResponseCode statusEnum) { return build(
statusEnum,null); } public synchronized static <T> ResponseResult<T> build(
ResponseCode responseCode, T data) { ResponseResult<T> res = new ResponseResult<
>(); res.setCode(responseCode.code); res.setMsg(responseCode.msg); res.setData(
data); return res; } public synchronized static <T> ResponseResult<T> ok() {
return build(ResponseCode.SUCCESS,null); } public synchronized static <T>
ResponseResult<T> okHasData(T data) { return build(ResponseCode.SUCCESS,data); }
private static final long serialVersionUID = 8992436576262574064L; }
<>2). use

Mainly in controller Used in :
import com.baomidou.mybatisplus.plugins.Page; import io.swagger.annotations.Api
; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.
ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework
.beans.factory.annotation.Autowired; import org.springframework.web.bind.
annotation.*; import com.xxx.xxx.dto.UserDTO; import com.xxx.xxx.entity.User;
import com.xxx.xxx.response.ResponseResult; import com.xxx.xxx.service.
IUserService; @RequestMapping("/user") @RestController @Api(tags = {" User action "})
public class UserController { @Autowired private IUserService userService;
@PostMapping("/list") @ApiOperation(" User list ") @ApiImplicitParam(paramType =
"header",name = "Authorization",value = " identity authentication Token") public ResponseResult<Page<
User>> list(@RequestBody @ApiParam(" Paging information ")UserDTO page){ Page<User> resultPage =
userService.selectPage(new Page<>(page.getPage(), page.getPageSize())); return
ResponseResult.okHasData(resultPage); } }

Technology
©2019-2020 Toolsou All rights reserved,
Python Basic knowledge and notes Programmer Tanabata Valentine's Day confession code NOI2019 travels China's longest high speed rail officially opened ! The fastest way to finish the race 30.5 hour C Language programming to find a student's grade Software testing BUG describe ESP8266/ESP32 System : Optimize system startup time Unity Scene loading asynchronously ( Implementation of loading interface ) Baidu , Ali , Tencent's internal position level and salary structure , With job suggestions !PYTHON Summary of final review