기사 디렉토리
1.0 우리는 왜 예외가 필요합니까
자바 예외에 대한, 당신은 내가 블로그를 작성하기 전에를 참조 할 수 있습니다 시스템 이상 및 프로젝트의 사용 - 자바 기초 (8) 비정상적인 사고와 어떻게 예외를 사용하는 방법이라 일부를.
왜 우리는 비정상적인 필요합니까?
나는 우리가 세 가지 다른 각도에서 생각 수 있다고 생각합니다.
- 백엔드 개발자 : 신속의 백엔드 개발자가 어디 프로그램에 로그인하여 문제 및 해결 문제에 위치합니다.
- 프런트 엔드 개발자 : 예외의 유형에 따라 적절한 스타일의 쇼를 할
- 사용자 : 어 어? ? 사용자가 기술을 이해하지 않는다, 당신은 예외의 유형은 단지 텍스트 또는 그래픽 메시지가 무엇인지 알 필요가 없습니다.
예를 들어, CSDN 업로드 프롬프트 네트워크 오류, 네트워크 내 옆에 아무 문제가 없습니다 파일,하지만 우리는 잘못된 네트워크 ID에 던져, 그래서 중이거나 내부 서버 오류입니다.
1.1 1.0 예외 처리
따라서, 후방 및 전방 단부 사이에 걸쳐 이상, 백 엔드가 예외를 발생 전면 요구 예외에 기초하여 상기 사용자에게 제시 다른 페이지를 보여주고, 이는 예외 처리의 가장 기본적인 방법은 :
2.0 처리 1.2 예외
이상 백엔드에 의해 생성 된 이후 포착 및 전환 비정상적인 말단부에 의해 본질적으로 1.0 모드에서는, 그때 가장 정확한 방법은 가지 예외 처리의 일부를 인출 후단에 의해 처리 될 . 현재의 방법 대신에 예외의 간단한 구현 상태 코드를 사용하는 것이다 :
후단의 예외 캡처 및 디스플레이 상태 코드에 의한 전단 가공에 대응하는 비정상 상태 코드로 처리 :
이것의 장점은 다음과 같습니다
백 엔드 예외 처리를 확인하십시오, 특정 정보가 예외를 노출 할 수 없습니다, 안전
2. 프론트 엔드 만 추가 예외없이, 상태 코드에 해당 페이지 점프 약속의 백 엔드를 기반으로 할 수 있습니다 프로세스는 단지 적절히 높은 응집력 낮은 결합의 목적을 달성 할 수있는 각 측 로직의 각각의 단부를 처리한다.
제 1 실시 예를 운반 1.3 예외
첫 번째 방법은 매우 간단하고 조잡 서비스 계층에서만 가능한 이상이 예외가 발생하는 경우, 다음 캡처의 경우 소수의 특이하다 컨트롤러 레이어에서 처리 :
템플릿 메시지 모듈과 함께 아래 프로젝트 SpringBoot / SSM 인 예외 처리를 사용하는 방법에 접촉하는 사고 과정은 컨트롤러의 이상 포착 및 처리에 통합 될 수있는 서비스 계층에서 발생 예외 및 층이다 :
- ArgsLoseException
/**
* @Auther: ARong
* @Description: 参数缺失异常
**/
public class ArgsLoseException extends Exception {
public ArgsLoseException(){}
public ArgsLoseException(String message){super(message);}
}
- ArgsErrorException
/**
* @Auther: ARong
* @Description: 参数错误异常
**/
public class ArgsErrorException extends Exception {
public ArgsErrorException() {}
public ArgsErrorException(String messasge) {super(messasge);}
}
- TemplateMessageSerivceImp
/**
* @Auther: ARong
* @Description: 发送模板消息
**/
@Service
@Transactional
@Slf4j
public class TemplateMessageSerivceImp implements TemplateMessageSerivce {
@Autowired
private MessageUtil messageUtil;
/**
* @param messageEntity
* @param opeType
* @auther: Arong
* @description: 注册成功后发送
* @param: [messageEntity]
* @return: AjaxResult
*/
@Override
public AjaxResult sendMessage(MessageEntity messageEntity, String opeType) throws ArgsLoseException, ArgsErrorException {
Map map = MessageUtil.MessageMap(
messageEntity.getOpenId(),
messageEntity.getPage(),
messageEntity.getFormId()
);
if (opeType == null || "".equals(opeType.trim())) {
throw new ArgsLoseException("opeType参数缺失");
}
if (!"YES".equals(opeType)) {
throw new ArgsErrorException("opeType参数错误");
}
//...业务逻辑
return null;
}
}
우리가 초점을 맞춘이 시점에서, 컨트롤러 레이어는 이러한 예외가 어떻게 처리하는 방법을해야 하는가?
첫째, 우리는 예외가 아니라 비정상적인 상태로 프런트 엔드 코드의 일종으로, 직접적으로 사용자의 눈에 노출 할 수 없습니다 것을주의 할 필요가 있으므로 프론트 엔드는 상태 코드에 따라 작동 사용자에게 메시지를 표시하기 위해, 예를 들어, 적절한 치료를 할 수 있다는 잘못된 것입니다 , 또는 사용자의 눈의 상태가 이상으로 짧은 초점 상태 코드 규칙 전후 단부에서 네트워크 지연 등 :
- TemplateMessageController
@Controller
@CrossOrigin
@RequestMapping(value = "/message")
@ResponseBody
@Slf4j
public class TemplateMessageController {
@Autowired
private TemplateMessageSerivce templateMessageSerivce;
/**
* @auther: Arong
* @description: 注册成功后发送
* @param: [messageEntity]
* @return: AjaxResult
*/
@PostMapping(value = "/sendMessage")
public AjaxResult sendMessage(
@ModelAttribute MessageEntity messageEntity,
@RequestParam(name = "opeType") String opeType //操作类型
) {
AjaxResult ajaxResult = null;
try {
ajaxResult = templateMessageSerivce.sendMessage(messageEntity, opeType);
} catch (Exception e) {
//打印异常栈堆路径
e.printStackTrace();
//分不同异常给前端返回不同的状态码(不要将异常暴露给前端,而是通过状态码让前端去反应)
if (e instanceof ArgsLoseException) {
//回传状态码501
return new AjaxResult(501, "传入opeType为空");
} else if (e instanceof ArgsErrorException) {
//回传状态码502
return new AjaxResult(502, "参数错误");
}
}
return ajaxResult;
},
}
소수의 예외를 처리 할 수있는 사용자 정의 방식으로 처리이 예외는 충분한 상태 일 때, 그러나로 점점 더 많은 사용자 정의 예외, 당신은 다음과 같이 더 이상 컨트롤러를 처리해야합니다
if (e instanceof ArgsLoseException) {
//回传状态码501
return new AjaxResult(501, "传入opeType为空");
} else if (e instanceof ArgsErrorException) {
//回传状态码502
return new AjaxResult(502, "参数错误");
} else if (e instanceof Xx1Exception) {
//...
} else if (e instanceof Xx2Exception) {
//...
} else if (e instanceof Xx3Exception) {
//...
}
그래서, 다음 필요성이 방식 예외 처리를 최적화
두 번째 방법을 처리 1.4 예외 - 글로벌 예외 핸들러
상술 과도한 경우 다른 문제 예외 처리 및 혼입 예외 처리 코드가 단순화 본원 SpringBoot 글로벌 예외 처리를 최적화하기 위해, 다음과 같은 특정 서비스 모듈에 관련되지 데모 프로그램은 단지 예시 적이다 :
- AjaxResult 리턴 결과
/**
* @Auther: ARong
* @Description: 处理结果
*/
@Data
public class AjaxResult {
public AjaxResult() {
}
public AjaxResult(int code, String message) {
this.code = code;
this.message = message;
}
private int code;
private String message;
}
- GlobalException 글로벌 예외, 내부 내부 클래스는 사용자 정의 예외를 정의
/**
* @Auther: ARong
* @Description: 全局异常定义
*/
public class GlobalException {
/*
* @Author ARong
* @Description 参数缺少异常
**/
@Data
public static class ArgsLoseException extends RuntimeException{
private int code = 501;
private String message;
public ArgsLoseException(String message) {
this.message = message;
}
}
/*
* @Author ARong
* @Description 参数错误异常
**/
@Data
public static class ArgsErrorException extends RuntimeException{
private int code = 502;
private String message;
public ArgsErrorException(String message) {
this.message = message;
}
}
}
- GlobalExceptionHandler
사용 @ControllerAdvice 및 @ExceptionHandler 글로벌 예외 핸들러를 달성
/**
* @Auther: ARong
* @Description: 全局异常处理器
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/*
* @Author ARong
* @Description 捕捉异常并进行处理
* @Param
* @return
**/
@ExceptionHandler(value = Exception.class)
public AjaxResult exceptionHandler(Exception e) {
// 打印异常调用栈
e.printStackTrace();
AjaxResult result = new AjaxResult();
int code = 500;
String message = "服务器出现错误";
// 如果是自定义异常则进行转化
if (e instanceof GlobalException.ArgsErrorException) {
// 参数错误异常
code = ((GlobalException.ArgsErrorException) e).getCode();
message = ((GlobalException.ArgsErrorException) e).getMessage();
}
if (e instanceof GlobalException.ArgsLoseException) {
// 参数缺失异常
code = ((GlobalException.ArgsLoseException) e).getCode();
message = ((GlobalException.ArgsLoseException) e).getMessage();
}
result.setCode(code);
result.setMessage(message);
return result;
}
}
- DemoController 제어 층
/**
* @Auther: ARong
* @Description: 控制层
*/
@Controller
@ResponseBody
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping(value = "/get")
public AjaxResult get(
@RequestParam(name = "id") String id
) {
AjaxResult result = demoService.get(id);
return result;
}
}
- DemoService 사업 층
/**
* @Auther: ARong
* @Description: 业务层
*/
@Service
public class DemoService {
public AjaxResult get(String id) {
if ("bug".equals(id)) {
// 参数错误
throw new GlobalException.ArgsErrorException("参数错误");
}
if ("null".equals(id)) {
// 参数缺失
throw new GlobalException.ArgsLoseException("参数缺失");
}
return new AjaxResult(200, "OK");
}
}
글로벌 예외 핸들러 캡처 할 필요에 제어기 층 및 정의 예외를 처리하고, 모든 대응하는 처리를 수행하고, 상태 코드를 상기 프로세서로 구성한 후. 우체부 간단한 테스트를 사용하여 프로젝트를 시작합니다 :
- 일반적으로
-
트리거 매개 변수 오류 예외
-
트리거 비정상적인 매개 변수가 누락
위의 단계 후에는 프로그램의 가독성을 향상시키기 위해, 매우 간단하고 덜 중복 부호 량 컨트롤러 레이어 될 기본 글로벌 예외 핸들러를 달성 할 수있는, 더 중요한 것은 나머지는 계약이 코드를 명시하는 방법이다 방법 프런트 엔드와 점프를 할.
감사
https://blog.csdn.net/Colton_Null/article/details/84592748