寫一個配置類攔截所有Exception
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionCatch {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult ExceptionHandle(Exception e) {
e.printStackTrace();
return ResponseResult.error("錯誤信息:"+e.getMessage()); // ResponseResult為我們自己封閉的實體類
}
}
攔截指定的異常用以下的方法(自定義的異常)
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseResult ExceptionHandle2(MyException e) {
final ResponseResult responseResult = new ResponseResult();
responseResult.setCode(e.getStatus().toString());
responseResult.setMessage(e.getMessage());
return responseResult;
}
