1. package com.xuecheng.common.exception;
    2. import com.xuecheng.common.domain.code.CommonErrorCode;
    3. import com.xuecheng.common.domain.code.ErrorCode;
    4. import com.xuecheng.common.domain.response.RestErrorResponse;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.springframework.http.HttpStatus;
    7. import org.springframework.web.bind.annotation.ControllerAdvice;
    8. import org.springframework.web.bind.annotation.ExceptionHandler;
    9. import org.springframework.web.bind.annotation.ResponseBody;
    10. import org.springframework.web.bind.annotation.ResponseStatus;
    11. /**
    12. * 日志:
    13. * 1.日志框架:{@link Slf4j}
    14. * 2.Slf4j 只是一个规范的Api没有实现类:使用 log4j2
    15. * 3.每一个类中如果要使用日志
    16. * private static final Logger log = xxx :创建一个日志对象
    17. * 4.Lombok使用 @Slf4j 来简化日志对象的创建
    18. *
    19. * 全局异常处理:
    20. * 1.全局异常处理的结构
    21. * 2.全局异常处理的实现技术
    22. * 3.异常处理的封装类
    23. * 4.对于异常的日志记录
    24. * 5.异常处理的过程
    25. * 向上寻找父类型
    26. */
    27. @Slf4j
    28. @ControllerAdvice
    29. public class GlobalExceptionHandler {
    30. /**
    31. * 处理可预知异常(业务模块中的异常信息)
    32. * @param businessException {@link BusinessException} 业务异常类
    33. * @return RestErrorResponse - 相应错误信息封装类,封装错误代码(code) 和 错误信息(desc)
    34. */
    35. @ResponseBody
    36. @ExceptionHandler(value = BusinessException.class)
    37. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    38. public RestErrorResponse customException(BusinessException businessException) {
    39. /*
    40. * error方法参数:
    41. * 1.错误信息
    42. * 在错误信息中可以使用占位符 :{}
    43. * 2.具体的错误内容
    44. * e.getMessage() 会把占位符进行替换
    45. * */
    46. log.error("【系统异常】{}", businessException.getMessage(), businessException);
    47. //1.获得异常信息属性
    48. ErrorCode errorCode = businessException.getErrorCode();
    49. //2.将异常信息属性的 错误代码(code) 和 错误信息(desc)封装到 RestErrorResponse 中
    50. return new RestErrorResponse(errorCode);
    51. }
    52. /**
    53. * 处理不可预知异常(微服务框架抛出不可预知异常类型)
    54. * @param exception {@link Exception} 异常类
    55. * @return RestErrorResponse - 相应错误信息封装类,封装错误代码(code) 和 错误信息(desc)
    56. */
    57. @ResponseBody
    58. @ExceptionHandler(value = Exception.class)
    59. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    60. public RestErrorResponse exception(Exception exception) {
    61. //0.将错误信息记录到日志中
    62. log.error("【系统异常】{}", exception.getMessage(), exception);
    63. //1.将异常信息属性的 错误代码(code) 和 错误信息(desc)封装到 RestErrorResponse 中
    64. return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKOWN.getCode()),
    65. CommonErrorCode.UNKOWN.getDesc() + ":" + exception.getMessage());
    66. }
    67. }

    ●@ExceptionHandler
    Spring3.0提供的标识在方法上或类上的注解,用来表明方法的处理异常类型。
    ●@ControllerAdvice
    Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强, 在项目中来增强SpringMVC中的Controller。通常和@ExceptionHandler 结合使用,来处理SpringMVC的异常信息。
    ●@ResponseStatus
    Spring3.0提供的标识在方法上或类上的注解,用状态代码和应返回的原因标记方法或异常类。 设置返回状态码例如404之类