需要引入依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
使用事例代码
package com.jm.domain;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.jm.validationGroup.Insert;
import lombok.Data;
@Data
public class Member {
/*
大苏打
*/
@NotBlank(groups = Insert.class,message = "名称不能为空")
@Size(min = 2,max = 5,message = "最小长度2,最大长度5")
private String name;
@NotBlank(message = "年级不能为空")
private String age;
@AssertTrue(message = "非男生")
private boolean sex;
}
@PutMapping
public String putMember( @Validated @RequestBody Member member){
System.out.println("member="+member);
int i = 1/Integer.parseInt(member.getAge());
return "putMember";
}
全局捕获异常
异常需要全局异常才能处理异常信息
package com.jm.exception.handler;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.jm.common.ServiceResult;
import com.jm.constant.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
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;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.util.List;
/**
* @author ZhangZungan
*/
@Slf4j
@RestControllerAdvice()
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ServiceResult handlerException(HttpServletRequest req, Exception e) {
log.error(e.getMessage(), e);
return ServiceResult.error(e.getMessage() == null ? e.toString() : e.getMessage());
}
@ExceptionHandler(FileNotFoundException.class)
public ServiceResult handlerException(HttpServletRequest req, FileNotFoundException e) {
log.error(e.getMessage());
return ServiceResult.error(CodeEnum.FAILURE, "文件不存在");
}
@ExceptionHandler(ArithmeticException.class)
public ServiceResult handlerException(HttpServletRequest req, ArithmeticException e){
log.error(e.getMessage());
return ServiceResult.error(CodeEnum.FAILURE, "算数运算异常");
}
/**
* 参数校验
*
* @param req 请求
* @param e 参数校验异常
* @return ServiceResult
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public ServiceResult handlerException(HttpServletRequest req, HttpMessageNotReadableException e) {
log.error(e.getMessage());
return ServiceResult.error(CodeEnum.INVALID_PARAMS, e.getMessage());
}
/**
* 参数校验
*
* @param req 请求
* @param e 参数校验异常
* @return ServiceResult
*/
@ExceptionHandler(InvalidFormatException.class)
@ResponseBody
public ServiceResult handlerException(HttpServletRequest req, InvalidFormatException e) {
log.error(e.getMessage());
return ServiceResult.error(CodeEnum.INVALID_PARAMS, "无效的数据格式!");
}
/**
* body参数校验(带@RequestBody注解)
*
* @param req 请求
* @param e 参数校验异常
* @return ServiceResult
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ServiceResult handlerException(HttpServletRequest req, MethodArgumentNotValidException e) {
log.error(toStr(e));
return ServiceResult.error(CodeEnum.INVALID_PARAMS, toStr(e));
}
/**
* query参数校验(不带@RequestBody注解)
*
* @param req 请求
* @param e 参数校验异常
* @return ServiceResult
*/
@ExceptionHandler(BindException.class)
@ResponseBody
public ServiceResult handlerException(HttpServletRequest req, BindException e) {
log.error(toStr(e));
return ServiceResult.error(CodeEnum.INVALID_PARAMS, toStr(e));
}
private String toStr(MethodArgumentNotValidException e) {
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
return "参数非法:" + fieldErrors.stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.reduce((s, s2) -> s + ", " + s2).orElse("");
}
private String toStr(BindException e) {
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
return "参数非法:" + fieldErrors.stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.reduce((s, s2) -> s + ", " + s2).orElse("");
}
}
package com.jm.common;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jm.constant.CodeEnum;
import lombok.Data;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
/**
* AjaxResult .
*
* @author xiaoyu
*/
@Data
public class ServiceResult<T> implements Serializable {
private static final long serialVersionUID = -2792556188993845048L;
private String code;
private String msg;
private T data;
/**
* Instantiates a new Soul result.
*/
public ServiceResult() {
}
/**
* Instantiates a new Soul result.
*
* @param code
* the code
* @param msg
* the message
* @param data
* the reqVo
*/
public ServiceResult(final String code, final String msg, final T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
/**
* return success.
*
* @return {@linkplain ServiceResult}
*/
public static ServiceResult success() {
return success("成功");
}
/**
* return success.
*
* @param msg
* msg
* @return {@linkplain ServiceResult}
*/
public static ServiceResult success(final String msg) {
return success(msg, null);
}
/**
* return success.
*
* @param data
* this is result reqVo.
* @return {@linkplain ServiceResult}
*/
public static <T> ServiceResult<T> success(final T data) {
return success(null, data);
}
/**
* return success.
*
* @param msg
* this ext msg.
* @param data
* this is result reqVo.
* @return {@linkplain ServiceResult}
*/
public static <T> ServiceResult<T> success(final String msg, final T data) {
return get(CodeEnum.OK.getCode(), msg, data);
}
/**
* return error .
*
* @param msg
* error msg
* @return {@linkplain ServiceResult}
*/
public static ServiceResult error(final String msg) {
return error(CodeEnum.FAILURE.getCode(), msg);
}
/**
* return error .
*
* @param code
* error code
* @param msg
* error msg
* @return {@linkplain ServiceResult}
*/
public static ServiceResult error(final String code, final String msg) {
return get(code, msg, null);
}
public static ServiceResult error(final CodeEnum codeEnum) {
return get(codeEnum.getCode(), codeEnum.getMsg(), null);
}
public static ServiceResult error(final CodeEnum codeEnum, final String msg) {
return get(codeEnum.getCode(), msg, null);
}
public static <T> ServiceResult<T> error(final CodeEnum codeEnum, final T data) {
return get(codeEnum.getCode(), codeEnum.getMsg(), data);
}
public static <T> ServiceResult<T> error(final CodeEnum codeEnum, final String msg, final T data) {
return get(codeEnum.getCode(), msg, data);
}
/**
* return timeout .
*
* @param msg
* error msg
* @return {@linkplain ServiceResult}
*
*/
public static ServiceResult timeout(final String msg) {
return error(CodeEnum.REQUEST_TIMEOUT.getCode(), msg);
}
private static <T> ServiceResult<T> get(final String code, final String msg, final T data) {
return new ServiceResult<>(code, msg, data);
}
public static void error(HttpServletResponse resp, String message) throws IOException {
error(resp, message, 500);
}
public static void error(HttpServletResponse resp, String message, Integer httpState) throws IOException {
error(resp, CodeEnum.FAILURE.getCode(), message, httpState);
}
public static void error(HttpServletResponse resp, String code, String message, Integer httpState) throws IOException {
resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
resp.setStatus(httpState);
PrintWriter out = resp.getWriter();
ServiceResult result = ServiceResult.error(code, message);
String str = new ObjectMapper().writeValueAsString(result);
out.write(str);
out.flush();
out.close();
}
public static void success(HttpServletResponse resp, String message) throws IOException {
success(resp, message, null);
}
public static <T> void success(HttpServletResponse resp, String message, T data) throws IOException {
resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
PrintWriter out = resp.getWriter();
ServiceResult result = ServiceResult.success(message, data);
String str = new ObjectMapper().writeValueAsString(result);
out.write(str);
out.flush();
out.close();
}
/**
* 根据service操作结果,返回成功或失败
* @param flag service操作结果
* @param message 失败时的提示信息
* @return ServiceResult
*/
public static ServiceResult result(boolean flag, String message){
if (flag) {
return success();
}
return error(message);
}
}
package com.jm.constant;
/**
* oes-live 全局响应码
*/
public enum CodeEnum {
UNKNOW_ERROR("-1", "未知错误"),
OK("0", "成功"),
FAILURE("1", "失败"),
REQUEST_TIMEOUT("408", "超时"),
INVALID_PARAMS("2", "请求参数无效"),
UNSUPPORTED_URI("3", "未知URI"),
UNQUANXIAN("403", "无权限操作"),
UNLOGIN("401", "账号或密码不正确"),
PARAMS_ERROR("1000","请求参数错误"),
DATABASE_ERROR("2002","数据库入库异常"),
DELETE_ERROR("2003", "删除失败"),
BATCH_DELETE_ERROR("2004", "未勾选,请选中后删除"),
JSON_ERROR("2010", "json转换异常"),
PARSE_DATETIME_ERROR("2011", "时间格式转换错误"),
CHANNEL_ERROR("9998","渠道分发错误"),
PARAMS_EMPTY("2101","请求参数为空"),
IS_EXIST("2103","信息已存在"),
ISNULL("2104","信息不存在"),
NOT_NUMBER("2105","必须为数字"),
PHOTO_MISS("2106","图片上传失败"),
PHOTO_SIZE_ERROR("2108","图片大小错误"),
PHOTO_FILE_ERROR("2109","图片文件错误"),
PHOTO_SPEC_ERROR("2110","图片规格错误"),
CAPTCHA_SEND_ERROR("2107","短信验证码发送失败"),
LOGIN_ERROR("2200", "账号或密码不正确"),
USER_FORBID("2201", "用户被禁用"),
INVALID_TOKEN("2202", "用户认证失败,请重新登录"),
EXPIRED_TOKEN("2203", "Token已过期,请重新登录"),
ISNULL_TOKEN("2204", "无效token,请重新登录"),
REPEATED_ADD("3202", "重复添加"),
USER_NOT_FOUND("3203", "用户不存在"),
USER_PASSWD_ERROR("3204", "用户密码不正确"),
USER_DEFAULT_PASSWD_ERROR("3205", "原密码不正确"),
USER_CODE_EXIST("3206", "工号已被使用"),
ROLE_REPEATED("3207", "角色名称重复"),
USER_DEPARTMENT_NAME_ERROR("3208", "部门名称错误"),
RESOURCE_REPEATED("3209", "角色名称重复"),
ROLE_NOT_FOUND("3210", "角色不存在"),
ROLE_PARAMS_ERROR("3211", "角色参数错误"),
EXPORT_USER_IS_NULL("3212", "导入信息为空"),
IMPORT_ERROR("4001", "Excel导入异常!"),
EXPORT_ERROR("4002", "Excel导出异常!"),
NULL_POINTER_ERROR("4003", "空指针异常"),
CAPTCHA_EXPIRED_ERROR("4004", "验证码已过期,请重新获取验证码"),
CAPTCHA_ERROR("4005", "验证码不正确"),
USER_LOCKED("4006", "该账号已被锁定4H"),
ERROR_FOUR("4007","您的密码已连续输入错误4次,输错5次将锁定账号4小时" ),
PSAA_ERROR("4008","用户名或密码错误" ),
USER_CHANGE_ERROR("4009","切换用户,请刷新页面重新登录" ),
CUSTON_ERROR("9999", " 其它,自定义错误");
private String code;
private String msg;
private CodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}