從零開始的SpringBoot項目 ( 七 ) 統一返回結果集Result 和 異常處理


import java.io.Serializable;
import lombok.Data;
import org.springframework.http.HttpStatus;

@Data
public class Result implements Serializable {

    private static final long serialVersionUID = -1802122468331526708L;

    private Integer code;// 狀態碼
    private String msg;// 返回信息
    private Object data;// 返回數據


    //自定義code,msg,data
    private Result(Integer code, String msg, Object data) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    //自定義data
    private Result(Object data) {
        this.data = data;
        this.code = HttpStatus.OK.value();
        this.msg = HttpStatus.OK.getReasonPhrase();
    }

    //自定義code,msg
    private Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private Result() {
        this.code = HttpStatus.OK.value();
        this.msg = HttpStatus.OK.getReasonPhrase();
    }

    public static Result success(Integer code, String msg, Object data) {
        return new Result(code, msg, data);
    }

    public static Result success(Integer code, String msg) {
        return new Result(code, msg);
    }

    public static Result error(Integer code, String msg) {
        return new Result(code, msg);
    }

    public static Result success(Object data) {
        return new Result(data);
    }

    public static Result success() {
        return new Result();
    }

}

Controller 層使用 Result

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my_springboot.user.pojo.UserInfoDO;
import com.my_springboot.user.service.IUserInfoService;
import com.my_springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用戶信息前端控制器
 * </p>
 *
 * @author JiHC
 * @since 2020-08-21
 */
@RestController
@RequestMapping("/user")
@Api(value = "UserInfoController", tags = {"用戶模塊"})
public class UserInfoController {

    @Autowired
    IUserInfoService userInfoService;

    @ApiOperation("新增用戶信息")
    @PostMapping(value = "/saveUser")
    public Result saveUser(@RequestBody UserInfoDO userInfoDO) {
        userInfoService.save(userInfoDO);
        return Result.success(HttpStatus.CREATED.value(), HttpStatus.CREATED.getReasonPhrase());
    }

    @ApiOperation("根據問題id修改問題")
    @PutMapping(value = "/updateUser")
    public Result updateUser(@RequestBody UserInfoDO userInfoDO) {
        String id = userInfoDO.getId();
        if (null == id || "".equals(id)) {// 無內容
            return Result
                    .error(HttpStatus.NO_CONTENT.value(), HttpStatus.NO_CONTENT.getReasonPhrase());
        }
        if (null==userInfoService.getById(id)) {// 未找到
            return Result
                    .error(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        userInfoService.updateById(userInfoDO);
        return Result.success();
    }

    @ApiOperation("根據id刪除用戶信息")
    @DeleteMapping(value = "/removeUser")
    @ApiImplicitParam(name = "id", value = "用戶id", dataType = "string", required = true, paramType = "query")
    public Result removeUser(@RequestParam String id) {
        if (null == id || "".equals(id)) {// 無內容
            return Result
                    .error(HttpStatus.NO_CONTENT.value(), HttpStatus.NO_CONTENT.getReasonPhrase());
        }
        if (null==userInfoService.getById(id)) {// 未找到
            return Result
                    .error(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase());
        }
        userInfoService.removeById(id);
        return Result.success();
    }

    @ApiOperation("信息")
    @PostMapping(value = "/listUserPage")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "當前頁碼", dataType = "int", required = true, paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每頁數量", dataType = "int", required = true, paramType = "query", defaultValue = "10")
    })
    public Result listUserPage(Integer pageNum, Integer pageSize) {
        Page<UserInfoDO> page = userInfoService.listUserPage(new Page(pageNum, pageSize));
        return Result.success(page);
    }
}

啟動項目訪問接口 訪問修改接口 , 輸入不存在的id , 期望返回404

 成功!

統一異常處理 : 

未添加異常處理時 , 參數錯誤的響應體 : 

 

 添加 控制器的異常處理類 ErrorHandler

import com.my_springboot.util.Result;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 *  控制器的異常處理類
 */
@ControllerAdvice
public class ErrorHandler {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ErrorHandler.class);

    /**
     * 輸入參數校驗異常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Result> NotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.debug("異常詳情 ", e);
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors() == false) {
            return null;
        }
        Map<String, String> fieldErrors = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getCode() + "|" + error.getDefaultMessage());
        }
        return new ResponseEntity<>(Result.error(422, "輸入錯誤", fieldErrors),
                HttpStatus.UNPROCESSABLE_ENTITY);
    }

    /**
     * 404異常處理
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<Result> NoHandlerFoundExceptionHandler(Exception e) {
        log.debug("異常詳情:", e);
        return new ResponseEntity<>(Result.error(404, "頁面丟失了!"), HttpStatus.NOT_FOUND);
    }

    /**
     * 默認異常處理,前面未處理
     */
    @ExceptionHandler(value = Throwable.class)
    public ResponseEntity<Result> defaultHandler(Exception e) {
        log.debug("異常詳情:", e);
        return new ResponseEntity<>(Result.error(500, "服務器錯誤:" + e),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

重啟項目 , 訪問 Swagger , 參數錯誤的響應體 : 

 

 配置成功 !

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM