package com.seckill.seckill.vo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@Getter
@AllArgsConstructor
@ToString
public enum respBeanEnum {
ERROR(500,"服务端异常"),
SUCCESS(200,"success") ;
private final Integer code;
private final String message;
}
package com.seckill.seckill.Exception;
import com.seckill.seckill.vo.respBeanEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
respBeanEnum respBeanEnum;
}
package com.seckill.seckill.Exception;
import com.seckill.seckill.vo.respBean;
import com.seckill.seckill.vo.respBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({GlobalException.class,BindException.class})
public respBean ExceptionHandler(Exception e){
if(e instanceof GlobalException){
GlobalException ge = (GlobalException) e;
return respBean.error(ge.getRespBeanEnum());
}else if(e instanceof BindException){
BindException be = (BindException) e;
respBean error = respBean.error(respBeanEnum.BINDING_ERROR);
error.setMessage("参数校验异常: "+be.getAllErrors().get(0).getDefaultMessage());
return error;
}
return respBean.error(respBeanEnum.ERROR);
}
}