简体   繁体   English

在Springboot中拦截异常的Rest api

[英]Rest api with intercept of Exception in Springboot

i have a rest api:我有一个休息 api:

@RestController

..... ......

@PostMapping(value = "/v1/ms/prop")
    public @ResponseBody ResponseEntity<Object> orch(@RequestBody @Valid Request request){
        
            
        

Response response = serv.prop(request);
            return ResponseEntity.ok(response);

and serv.prop(request):和 serv.prop(请求):

Response response = new Response ();
    
    try {
        calculate(**data**);
        callExternalService();
    } catch (Exception e) {

   **//intercept status error code**
   **// writeError(data,errorStatusCode)**
        
    } finally {
        writeAuditOperation(auditLog);
        MDC.clear();
    }

Inside the catch, i want, ONLY IN this api rest, intercept the type of error (400,404,500,502 ecc ecc ) and call an external service that log this error.在 catch 内部,我只想在这个 api rest 中拦截错误类型(400,404,500,502 ecc ecc)并调用记录此错误的外部服务。

Thanks for the help谢谢您的帮助

Rather than manually handling Exceptions in your controller, you should try @ExceptionHandler .与其在控制器中手动处理异常,不如尝试@ExceptionHandler

Check: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc检查: https ://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM