spring boot框架搭建-5 自定义异常以及全局异常捕捉
自定义了返回值之后,再自定义异常以及全局异常捕捉,自定义异常:
package com.example.wx.common.core.exception;
import com.example.wx.common.core.ret.RetCode;
/**
* 自定义异常
* Created by w on 2019/3/1.
*/
public class MyException extends RuntimeException{
//状态码默认500
private int statusCode = RetCode.INTERNAL_SERVER_ERROR;
public MyException(int statusCode,String message) {
super(message);
this.statusCode = statusCode;
}
public MyException(String message) {
super(message);
}
public int getStatusCode() {
return statusCode;
}
}
再捕捉异常以自定义返回值返回给前端
package com.example.wx.common.core.exception;
import com.example.wx.common.core.ret.ApiResult;
import com.example.wx.common.core.ret.RetCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Created by w on 2019/3/1.
*/
@RestControllerAdvice//全局异常处理
public class MyExceptionHandler {
/**
* 业务异常返回
* ExceptionHandler 统一处理某一类异常,从而能够减少代码重复率和复杂度
*/
@ExceptionHandler(MyException.class)
public ApiResult handleRRException(MyException e) {
ApiResult apiResult = new ApiResult(e.getStatusCode(), e.getMessage());
return apiResult;
}
/**
* 未捕捉异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public ApiResult handleException(Exception e) {
ApiResult r = new ApiResult(RetCode.INTERNAL_SERVER_ERROR, "未知错误");
if(e instanceof IllegalArgumentException){
r.setCode(RetCode.FAIL);
r.setMsg("不合法的参数");
}
e.printStackTrace();
return r;
}
}
自定义异常以及异常捕捉搞定之后,我们就可以测试了,
控制层代码
package com.example.wx.controller;
import com.example.wx.common.core.exception.MyException;
import com.example.wx.common.core.ret.ApiResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by w on 2019/2/28.
*/
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/demo")
ApiResult demo(@RequestParam String name)
{
ApiResult apiResult = new ApiResult();
apiResult.setData(name);
return apiResult;
}
//异常测试
@RequestMapping("/test")
ApiResult test()
{
throw new MyException("自定义异常测试");
}
}
测试出一下结果就是正确了
上一篇,spring boot框架搭建-4 自定义返回值
下一篇,spring boot框架搭建-6 链接mysql以及配置jpa