自定义全局异常处理

package cn.stevekung.error;
// 自定义 业务异常
public class BusinessException extends RuntimeException {
    public BusinessException(){}

    public BusinessException(String message) {
        super(message);
    }
}
package cn.stevekung.error;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErrorInfo {
    public static final Integer SUCCESS = 200;
    public static final Integer ERROR = 100;


    //错误码
    private Integer code;
    //错误信息
    private String message;

    private String url;
    private T data;
}

@ControllerAdvice(basePackages={"cn.stevekung",})

package cn.stevekung.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(basePackages={"cn.stevekung",})
public class GlobalDefaultExceptionHandler {
    @ExceptionHandler({BusinessException.class}) // 需要处理的异常类型
    //如果返回的为json数据或其它对象,添加该注解
    @ResponseBody
    public ErrorInfo defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setUrl(req.getRequestURI());
        errorInfo.setCode(ErrorInfo.SUCCESS);
        return errorInfo;
    }
}
  @RequestMapping("/findAll")
    public String findAll(Model model) {
        List ayUser = ayUserService.findAll();
        model.addAttribute("users",ayUser);
        //
        throw new BusinessException("业务异常");
    }

 

你可能感兴趣的:(java,自定义全局异常处理)