`

自定义异常,异常Advice,restTemplate异常处理

阅读更多
http://blog.sizovs.net/spring-rest-exception-handler/

1.自定义异常
public class MyException extends RuntimeException{

    public MyException(String message) {
        super(message);
    }
}


@ResponseStatus(HttpStatus.NOT_FOUND)
public class MyNotFoundException extends MyException {
    public MyNotFoundException(String content,Object keyword) {
        super(String.join(": ","找不到"+content+",关键字", keyword.toString()));
    }
}


2.异常处理
@ControllerAdvice
public class ExceptionHandlerAdvice {
    /*******************************************
     * 自定义异常处理
     *************************************************/
    @ExceptionHandler(MyException.class)
    ResponseEntity<MyExceptionRepresentation> myExceptionHandle(MyException e) {
        HttpStatus responseStatus = resolveAnnotatedResponseStatus(e);
        MyExceptionRepresentationbody = new MyExceptionRepresentation(e, responseStatus);
        return new ResponseEntity<>(body, responseStatus);
    }


    /*******************************************
     * 其他已知异常,消息定制化处理
     ************************************************/
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    ResponseEntity<MyExceptionRepresentation> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        String message = String.join("参数的错误输入: ", e.getName(), e.getValue().toString());
        MyExceptionRepresentation body = new MyExceptionRepresentation(e,message, HttpStatus.BAD_REQUEST);
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    ///解析状态码
    public static HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
        ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
        if (annotation != null) {
            return annotation.value();
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

@Data
class MyExceptionRepresentation {
    private boolean myException= true;
    private Date timestamp;
    private int status;
    private String error;
    private String exception;
    private String message;
    private String path;

    public MyExceptionRepresentation(Exception e, HttpStatus responseStatus) {
        this(e, e.getLocalizedMessage(),responseStatus);
    }

    public MyExceptionRepresentation(Exception e, String message, HttpStatus responseStatus) {
        this.timestamp = new Date();
        this.status = responseStatus.value();
        this.error = responseStatus.getReasonPhrase();
        this.exception = e.getClass().getName();
        this.message = message;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        this.path = request.getServletPath();
    }
}


3.RestTempldate处理异常
public class MyErrorHandler implements ResponseErrorHandler {  
    @Override  
    public void handleError(ClientHttpResponse response) throws IOException {  
       String e = CharStreams.toString(new InputStreamReader(response.getBody()));  
        JSONObject exception = JSONObject.fromObject(e);  
        boolean myException = (boolean) exception.getOrDefault("myException", false);  
        if (myException) {
            throw new RuntimeException((String) exception.get("message"));  
        } else {  
            throw new RuntimeException(exception.toString()); 
        }  
    }  
}  


public class RestTemplateTest {

    RestTemplate restTemplate;

    @Before
    public void setUp(){
        restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new MyErrorHandler());
    }

    @Test
    public void testSuccessAndMyException() {
//        String url = "http://localhost:9124/course/list/试用期";
        String url = "http://localhost:9124/course/list/试用";
        try {
            Arrays.stream(restTemplate.getForObject(url, Course[].class))
                .map(Course::getName)
                .forEach(System.out::println);
        } catch (MyException e) {
            System.out.println(e.getMessage());
            System.out.println(e.getExceptionName());
        }
    }
}
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    用户自定义异常.rar

    对于异常处理,我们可以使用`@AfterThrowing`注解来捕获并处理异常: ```java import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.springframework....

    利用springmvc切面捕获全局异常入库源码

    通过创建自定义切面和后置通知,可以捕获任何未被特定控制器方法处理的异常,并将这些异常信息存入数据库,提供了一种高效且全面的异常管理解决方案。这个实践对于构建健壮的、有弹性的Web应用具有很高的参考价值。

    spring mvc异常简单处理

    这样做的好处是,我们可以在一个集中的地方处理异常,而不是让它们传播到整个应用程序。 接下来,Spring MVC提供了`@ControllerAdvice`注解,它允许我们定义全局的异常处理器。这样的类可以包含多个`@...

    spring boot demo (包括异常处理 aop redis的整合)

    在"spring boot demo"项目中,你将找到关于异常处理、AOP(面向切面编程)以及 Redis 整合的实践示例。 **异常处理**在Spring Boot中通常通过`@ControllerAdvice`和`@ExceptionHandler`注解实现。`@...

    基于 Spring Boot 编写出的统一返回数据结构处理和统一异常处理的插件

    基于 Spring Boot 编写出的统一返回数据结构处理和统一异常处理的插件 使用之前,首先:不要使用Object类型返回,否则返回为null时,不会拦截到** 配置项 # 根注释 veedo: # 统一拦截配置模块 ragdoll: # 统一...

    Java AOP 公共异常处理,一个没有try的项目。.zip

    3. **通知(Advice)**:在特定连接点执行的代码,也就是我们处理异常的逻辑。Spring提供了五种类型的通知:前置通知(Before)、后置通知(After)、返回后通知(After Returning)、抛出异常后通知(After ...

    使用Spring进行统一日志管理 + 统一异常管理

    首先,我们定义了一个 ExceptionAdvisor 类,该类实现了 ThrowsAdvice 接口,该接口是 Spring 中的一个Advice 接口,用于处理异常情况。在 afterThrowing 方法中,我们使用 Log4j 来记录异常信息,并将其输出到...

    spring.net结合三层AOP异常日志记录功能

    在异常情况下,可以定义一个切面来捕获并处理异常,同时记录日志。 4. **异常日志记录**:日志记录是系统故障排查的重要手段。我们可以创建一个自定义的日志类,实现IAdvice接口,这样Spring.NET就能在发生异常时...

    spring自定义注解样例

    System.out.println("在执行方法前,处理自定义注解:" + customAnnotation.value()); Object result = joinPoint.proceed(); // 执行原方法 System.out.println("在执行方法后,处理自定义注解:" + custom...

    spring自定义切面实例

    切面类需要使用`@Aspect`注解进行标记,并包含不同的通知类型(Advice)方法,这些方法将在特定的连接点(Join Point)执行。常见的通知类型包括: - `@Before`:在目标方法执行前调用。 - `@After`:无论目标方法...

    spring-boot-rest-exceptions:使用Spring Boot的Rest Controller中的自定义错误格式和异常处理

    使用Spring Boot处理REST控制器中的错误目标该示例代码显示了如何配置Spring Boot应用程序以正确处理所有异常并创建自定义错误格式。 查看ThePracticalDeveloper网站上的以获取带有说明的完整指南。 并且,如果您...

    Spring AOP - Advice

    3. **After(Throwing)Advice**:当目标方法抛出异常时执行,通常用于处理异常或记录错误信息。 4. **Around Advice**:这是最强大的Advice类型,它包围了目标方法的整个生命周期,包括方法调用前后以及异常处理。...

    Spring异常捕获且回滚事务解决方案

    如果方法中抛出异常,那么 AOP 代理将捕获该异常,并对其进行处理。 但是,如果我们在方法中捕获了异常,那么 AOP 代理将不会捕获该异常。这是因为 AOP 代理只能捕获未被捕获的异常。如果我们想让 AOP 代理捕获异常...

    SpringMVC利用AOP实现自定义注解记录日志

    切面可以理解为一系列相互关联的方法和通知(advice)的集合,这些方法会在特定的连接点(join point)执行,如方法调用前、后或异常发生时。 在Spring中,定义一个自定义注解,比如`@Loggable`,用于标记需要记录...

    springmvc机制

    - **自定义异常**:开发者可以自定义异常类,并通过异常处理器来处理这些异常。 - **异常映射**:通过配置异常映射来定义不同异常与视图之间的关系,以便于更好地控制异常发生后的页面跳转。 ### 结论 Spring MVC ...

    spring aop 自定义切面示例

    Spring支持五种不同类型的通知:前置通知(before)、后置通知(after)、返回后通知(after returning)、异常后通知(after throwing)和环绕通知(around)。例如,我们可以创建一个切面类`LoggingAspect`: ```...

    SpringBoot AOP各种注解、自定义注解、鉴权使用案例(免费下载)

    自定义注解通常用于标记需要特殊处理的方法。例如,创建一个名为`@Cacheable`的自定义注解,用于缓存方法的返回结果: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface...

    The C++ Programming Language(ch 14)

    这对于那些不需要立即处理异常的情况很有用,例如在构造函数中发生异常时,可以将其重新抛出以便在更高层次上处理。 #### 14.6 资源管理 [except.resource] 资源管理是异常处理中的一个重要概念,尤其是在自动资源...

    spring中自定义注解(annotation)与AOP中获取注解

    通过这种方式,我们可以在AOP中灵活地处理带有自定义注解的方法,实现如日志记录、性能监控、权限验证等多种功能。这不仅提高了代码的复用性,也使得业务逻辑更加清晰。 总结来说,Spring中的自定义注解和AOP的结合...

Global site tag (gtag.js) - Google Analytics