1.编写自动异常类,Spring 对于 RuntimeException类的异常才会进行事务回滚,所以我们一般自定义异常都继承该异常类。
package com.developlee.errorhandle.exception;
/**
* @author Lensen
* @desc 自定义异常类
* @since 2018/10/5 11:04
*/
public class CustomException extends RuntimeException {
private long code;
private String msg;
public CustomException(Long code, String msg){
this.code = code;
this.msg = msg;
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2.编写全局异常处理类
package com.itstyle.seckill.common.exception;
import com.itstyle.seckill.common.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
/**
* 异常处理器
*/
@ControllerAdvice
public class RrExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(CustomException .class)
@ResponseBody
public Result handleException(CustomException e){
logger.error(e.getMessage(), e);
return Result.error();
}
@ExceptionHandler(Exception.class)
@ResponseBody
public Result handleException(Exception e){
logger.error(e.getMessage(), e);
return Result.error();
}
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Result runtimeException(RuntimeException e) {
logger.error("运行时异常:", e);
return Result.error("运行时异常");
}
}
3.在controller中抛出自定义异常
@Controller
public class DemoController {
/**
* 关于@ModelAttribute,
* 可以使用ModelMap以及@ModelAttribute()来获取参数值。
*/
@GetMapping("/one")
public String testError(ModelMap modelMap ) {
throw new CustomException (500L, "系统发生500异常!" + modelMap.get("attribute"));
}
}