当前位置:首页 > 后端开发 > 正文

Java如何获取异常错误码?

在Java中,可通过捕获异常后调用 getMessage()获取异常信息;针对特定异常(如 SQLException),使用 getErrorCode()直接获取错误码,一般流程: try-catch捕获异常,判断异常类型后调用对应方法。

标准异常码的获取方式

Java标准异常本身不直接提供“异常码”,但可通过以下方法提取关键信息:

  1. getMessage() 方法
    返回异常的详细描述字符串(含部分错误信息):

    Java如何获取异常错误码?  第1张

    try {
        int num = Integer.parseInt("abc"); // 触发NumberFormatException
    } catch (NumberFormatException e) {
        System.out.println("异常信息: " + e.getMessage()); 
        // 输出:For input string: "abc"
    }
  2. toString()getClass().getName()
    获取异常类名和消息:

    catch (Exception e) {
        System.out.println("异常类型: " + e.getClass().getName()); 
        // 输出:java.lang.NumberFormatException
    }

自定义异常码(推荐实践)

通过继承异常类实现自定义错误码:

// 1. 定义含错误码的异常类
public class CustomException extends Exception {
    private final int errorCode; // 自定义异常码
    public CustomException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    public int getErrorCode() {
        return errorCode;
    }
}
// 2. 使用并获取异常码
try {
    throw new CustomException(1001, "文件读取失败");
} catch (CustomException e) {
    System.out.println("错误码: " + e.getErrorCode()); // 输出:1001
    System.out.println("错误信息: " + e.getMessage()); // 输出:文件读取失败
}

第三方库的异常码

如Spring、Hibernate等框架常封装标准异常码:

// 示例:Spring的响应状态码
try {
    restTemplate.getForEntity("https://invalid-url", String.class);
} catch (HttpClientErrorException e) {
    System.out.println("HTTP状态码: " + e.getStatusCode().value()); // 输出:404
}

JVM错误码(非异常场景)

程序退出时通过 System.exit() 返回状态码:

public static void main(String[] args) {
    try {
        // 业务逻辑
    } catch (Exception e) {
        System.exit(1); // 返回错误码1给操作系统
    }
}

关键注意事项

  1. 优先使用标准异常:如 IllegalArgumentExceptionIOException 等,避免过度自定义。
  2. 日志记录:结合日志框架(如SLF4J)输出异常码和堆栈:
    catch (Exception e) {
        logger.error("错误码: {} - 详情: {}", customCode, e.getMessage(), e);
    }
  3. 避免敏感信息:异常消息中禁止包含密码、密钥等数据(OWASP规范)。

  • 标准异常:通过 getMessage()getClass() 提取信息。
  • 自定义异常:继承异常类并添加 errorCode 字段(最灵活)。
  • 框架异常:调用框架提供的API(如 getStatusCode())。
  • 系统错误码:通过 System.exit() 返回给操作系统。

引用说明:本文代码示例遵循Oracle官方Java规范,自定义异常设计参考《Effective Java》条目72,第三方库用法基于Spring Framework 5.3文档,安全规范引用OWASP错误处理指南。

0