新建一个切面即可:
package com.haerwang.springboot.exceptionHandler;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author haerwang
* @ControllerAdvice 标识这个类是切面
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseBody//拦截后返回给前端的是json格式
public Map<String, Object> exceptionHandler(RuntimeException e) {
Map<String, Object> reslut = new HashMap<String, Object>();
reslut.put("code", 500);
return reslut;
}
}