统一返回结果:
package com.caffebabe.codelife.controller;
import com.caffebabe.codelife.util.ErrorEnum;
import com.caffebabe.codelife.util.UniformException;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Result<T> {
private boolean success = true;
private int code = ErrorEnum.SUCCESS.getErrorCode();
private String msg = ErrorEnum.SUCCESS.getErrorMsg();
private T data;
public Result(T data) {
this.data = data;
}
public Result(Boolean success, Integer code, String msg, T data) {
this(success, code, msg);
this.data = data;
}
public Result(Boolean success, Integer code, String msg) {
this.success = success;
this.code = code;
this.msg = msg;
}
public static Result<?> uniError(UniformException e) {
Result<?> result = new Result<>(false, e.getErrorCode(), e.getErrorMsg());
return result;
}
public static Result<?> otherError(ErrorEnum errorEnum) {
Result<?> result = new Result<>(errorEnum);
result.setMsg(errorEnum.getErrorMsg());
result.setCode(errorEnum.getErrorCode());
result.setSuccess(false);
result.setData(null);
return result;
}
}
常见错误码
package com.caffebabe.codelife.util;
/**
* ErrorEnum 定义了常见的系统错误码
*
* <pre>
* 200-成功
* 403-没有权限
* 401-没有认证
* 400-请求错误
* 404-未找到该资源
* 500-服务器未知错误
* </pre>
*/
public enum ErrorEnum {
/** 200-成功 */
SUCCESS(200, "成功"),
/** 403-没有权限 */
NO_PERMISSION(403, "没有权限"),
/** 401-没有认证 */
NO_AUTH(401, "没有认证"),
/** 404-未找到该资源 */
NOT_FOUND(404, "未找到该资源!"),
/** 400-请求错误 */
BAD_REQUEST(400, "请求错误!"),
/** 500-服务器未知错误 */
INTERNAL_SERVER_ERROR(500, "服务器未知错误");
/** 错误码 */
private Integer errorCode;
/** 错误信息 */
private String errorMsg;
ErrorEnum(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
统一业务异常定义:
package com.caffebabe.codelife.util;
public class UniformException extends RuntimeException {
private static final long serialVersionUID = 1L;
protected Integer errorCode;
protected String errorMsg;
public UniformException() {
}
public UniformException(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
处理validate错误
package com.caffebabe.codelife.controller;
import com.caffebabe.codelife.util.ErrorEnum;
import com.caffebabe.codelife.util.UniformException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义异常
*
* @param e UniformException
* @return
*/
@ExceptionHandler(value = UniformException.class)
@ResponseBody
public Result<?> bizExceptionHandler(UniformException e) {
return Result.uniError(e);
}
/**
* 处理MethodArgumentNotValidException异常
*
* @param e 在rapplication/json格式提交,校验失败时抛出
* @return
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result<?> errorHandler(MethodArgumentNotValidException e) {
var errorMsg = new StringBuilder();
var re = e.getBindingResult();
for (ObjectError error : re.getAllErrors()) {
String[] codes = error.getCodes();
String code = codes[0];
errorMsg.append(code.substring(code.lastIndexOf(".") + 1));
errorMsg.append(error.getDefaultMessage()).append(",");
}
errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
Result<?> result = new Result<>(false, ErrorEnum.BAD_REQUEST.getErrorCode(), errorMsg.toString());
return result;
}
/**
* 处理BindException异常,表单提交时抛出
*
* @param bindException
* @return
*/
@ExceptionHandler(value = BindException.class)
public Result<?> errorHandler(BindException bindException) {
BindingResult br = bindException.getBindingResult();
StringBuilder errorMsg = new StringBuilder();
for (ObjectError error : br.getAllErrors()) {
errorMsg.append(error.getDefaultMessage()).append(",");
}
errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
Result<?> result = new Result<>(false, ErrorEnum.BAD_REQUEST.getErrorCode(), errorMsg.toString());
return result;
}
/**
* 处理其他异常
*
* @param e Exception
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result<?> exceptionHandler(Exception e) {
return Result.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
}
}
请求示例
package com.caffebabe.codelife.controller;
import javax.validation.Valid;
import com.caffebabe.codelife.entity.Book;
import com.caffebabe.codelife.service.BookService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public Result<PageInfo<Book>> getBookPage(@RequestParam("page_num") int pageNum,
@RequestParam("page_size") int pageSize) {
var page = bookService.findPage(pageNum, pageSize);
Result<PageInfo<Book>> result = new Result<>(page);
return result;
}
@PostMapping
public Result<?> addBook(@Valid @RequestBody Book book) {
bookService.addBook(book);
return new Result<>(null);
}
}