当前位置: 首页 > 知识库问答 >
问题:

在控制器通知中获取控制器名称和java服务路径

吴举
2023-03-14
@GetMapping(value = "DynamoDb/deleteTable")
public String deleteTable(@RequestParam String TableName) throws InterruptedException {
     Table table = dynamoDB.getTable(TableName);
        try {
            table.delete();
            table.waitForDelete();
        } catch (Exception e) {
            throw e;
        }
        return "Success";
    }
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;

import java.util.Arrays;

@ControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
        ErrorResponse error = new ErrorResponse();
        error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        error.setMessage(ex.getMessage());
        error.setController(ex.getMessage());
        error.setService(ex.getMessage());
        error.setTimestamp(System.currentTimeMillis());
        PutLogEvents(error);
        return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
    }

    public static void PutLogEvents(ErrorResponse Er)
    {
        String regionId = "us-east-1";
        String logGroupName = "xxxxxxx";
        String logStreamName = "xxxxxxx";

        CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder().region(Region.of(regionId)).build();

        // A sequence token is required to put a log event in an existing stream.
        // Look up the stream to find its sequence token.
        String sequenceToken = getNextSequenceToken(logsClient, logGroupName, logStreamName);

        // Build a JSON log using the EmbeddedMetricFormat.

        String message = "[{" +
                "  \"Timestamp\": " + Er.getTimestamp()  + "," +
                "  \"ErrorCode\": " + Er.getErrorCode()  + "," +
                "  \"ControllerName\": " + Er.getErrorCode()  + "," +
                "  \"ServiceName\": " + Er.getErrorCode()  + "," +
                "  \"ErrorMsg\": " + Er.getErrorCode()   + "" +
                "}]";
        InputLogEvent inputLogEvent = InputLogEvent.builder()
                .message(message)
                .timestamp(Er.getTimestamp())
                .build();

        // Specify the request parameters.
        PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder()
                .logEvents(Arrays.asList(inputLogEvent))
                .logGroupName(logGroupName)
                .logStreamName(logStreamName)
                // Sequence token is required so that the log can be written to the
                // latest location in the stream.
                .sequenceToken(sequenceToken)
                .build();

        logsClient.putLogEvents(putLogEventsRequest);
    }

    private static String getNextSequenceToken(CloudWatchLogsClient logsClient, String logGroupName, String logStreamName) {
        DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder()
                .logGroupName(logGroupName)
                .logStreamNamePrefix(logStreamName)
                .build();

        DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest);

        // Assume that a single stream is returned since a specific stream name was
        // specified in the previous request.
        return describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken();
    }

}
public class ErrorResponse {
    private int errorCode;
    private String message;
    private String Controller;
    private String Service;
    private String ProjectName;
    private long Timestamp;

    public ErrorResponse(int errorCode, String message, String controller, String service, String projectName, long timestamp) {
        this.errorCode = errorCode;
        this.message = message;
        Controller = controller;
        Service = service;
        ProjectName = projectName;
        Timestamp = timestamp;
    }

    public ErrorResponse() {

    }

    @Override
    public String toString() {
        return "ErrorResponse{" +
                "errorCode=" + errorCode +
                ", message='" + message + '\'' +
                ", Controller='" + Controller + '\'' +
                ", Service='" + Service + '\'' +
                ", ProjectName='" + ProjectName + '\'' +
                ", Timestamp=" + Timestamp +
                '}';
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getController() {
        return Controller;
    }

    public void setController(String controller) {
        Controller = controller;
    }

    public String getService() {
        return Service;
    }

    public void setService(String service) {
        Service = service;
    }

    public String getProjectName() {
        return ProjectName;
    }

    public void setProjectName(String projectName) {
        ProjectName = projectName;
    }

    public long getTimestamp() {
        return Timestamp;
    }

    public void setTimestamp(long timestamp) {
        Timestamp = timestamp;
    }
}


共有1个答案

杭志泽
2023-03-14

嗨,感谢所有通过使用下面的代码,我能够得到客户建议的结果。希望这能帮助到一些人。谢谢

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.PutLogEventsRequest;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;

@ControllerAdvice
public class ExceptionControllerAdvice {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    @Value("${application.name}")
    private String applicationName;

    @Value("${aws.logGroupName}")
    private String logGroupName;

    @Value("${aws.logStreamName}")
    private String logStreamName;


    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex, HandlerMethod handlerMethod, HttpServletRequest request) throws JsonProcessingException {
        Class ControllerName = handlerMethod.getMethod().getDeclaringClass();
        String MethodName = handlerMethod.getMethod().getName();
        ErrorResponse error = new ErrorResponse();

        error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        error.setErrorMessage(ex.getMessage());
        error.setControllerName(ControllerName.toString());
        error.setServiceName(MethodName.toString());
        error.setTimeStamp(sdf.format(System.currentTimeMillis()));
        error.setProjectName(applicationName);
        error.setServicePath(request.getRequestURL().toString());
        PutLogEvents(error);

        return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
    }

    public void PutLogEvents(ErrorResponse Er) throws JsonProcessingException {
        String regionId = "xxxxx";
        String logGroupName = "xxxxx";
        String logStreamName = "xxxxx";

        CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder().region(Region.of(regionId)).build();
        // A sequence token is required to put a log event in an existing stream.
        // Look up the stream to find its sequence token.
        String sequenceToken = getNextSequenceToken(logsClient, logGroupName, logStreamName);

        // Build a JSON log using the EmbeddedMetricFormat.

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = ow.writeValueAsString(Er);

        String message =json;
        InputLogEvent inputLogEvent = InputLogEvent.builder()
                .message(message)
                .timestamp(System.currentTimeMillis())
                .build();

        // Specify the request parameters.
        PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder()
                .logEvents(Arrays.asList(inputLogEvent))
                .logGroupName(logGroupName)
                .logStreamName(logStreamName)
                // Sequence token is required so that the log can be written to the
                // latest location in the stream.
                .sequenceToken(sequenceToken)
                .build();

        logsClient.putLogEvents(putLogEventsRequest);
    }

    private static String getNextSequenceToken(CloudWatchLogsClient logsClient, String logGroupName, String logStreamName) {
        DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder()
                .logGroupName(logGroupName)
                .logStreamNamePrefix(logStreamName)
                .build();

        DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest);

        // Assume that a single stream is returned since a specific stream name was
        // specified in the previous request.
        return describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken();
    }

}

结果应该是这样的

{
    "errorMessage": "Table already exists: ProductFgh (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ResourceInUseException; Request ID: 6S14VS0E6ESUMG55DL937IC42JVV4KQNSO5AEMVJF66Q9ASUAAJG)",
    "timeStamp": "2020-Jan-22 11:53:58",
    "errorCode": 500,
    "projectName": "DynamoDB",
    "servicePath": "http://localhost:8090/DynamoDb/createTable",
    "controllerName": "class com.example.DynamoDB.DynamoDBController",
    "serviceName": "createExampleTable"
}

到目前为止,我已经通过上面的代码实现了这一点,如果有更好的方法可用,让我知道。感谢所有人

 类似资料:
  • 对于我们的web应用程序,我需要保存获取和显示的项的顺序,这取决于视图--或者准确地说--生成视图的控制器和操作(当然还有用户id,但这不是这里的重点)。 我认为,与其在每个控制器操作中自己给出一个标识符(以便使用它对DB输出进行视图依赖的排序),不如从控制器和操作方法中自动创建这个标识符更安全、更容易。 如何从控制器的操作方法中获取控制器和操作的名称?还是我需要反思?

  • 问题内容: 有没有办法从AngularJS中的当前$ scope中获取控制器名称? 问题答案: 不,不可能。如果属于指令怎么办?没有属性可以检索有关该范围所属的控制器的信息。

  • 问题内容: 我试图在我的应用程序中编写通用路由,并根据路由参数动态解析视图和控制器名称。 我有以下有效的代码: 但是,我无法找到一种动态解析控制器名称的方法。我尝试使用此处所述的方法,但是ui- router似乎处理处理的方式与angular- route不同。 有指针吗? 编辑 :我已经尝试使用,但是对我不起作用(例如,以下代码仅返回一个硬编码的控制器名称,以测试其是否真正起作用): 给我以下错

  • 本文向大家介绍Asp.net MVC中获取控制器的名称的方法,包括了Asp.net MVC中获取控制器的名称的方法的使用技巧和注意事项,需要的朋友参考一下 1、视图中   2、控制器的action中 3、过滤器中   比如在ActionFilterAttribute中,这个时候一般是自己实现一个继承类,然后重写相关的方法。   在重写的方法中如果需要控制器的名称。 4、公共方法中 以上所述是小编给

  • 问题内容: 我想基于我们加载的配置动态指定一个控制器。像这样: 我该怎么做呢?我以为这很容易,但是我似乎可以找到一种方法。 问题答案: 您想要做的是在调用其他指令之前先运行另一个指令,从某个模型获取控制器名称,然后删除新指令并添加指令,然后重新编译元素。 看起来像这样: 然后,您可以在模板中使用它,如下所示: 使用这样的控制器: 可能有一种插值的值()而不是解析它()的方法,但是由于某种原因,我无

  • 问题内容: 我已经阅读了几篇有关angularjs实体正确用法的文章:服务,工厂,控制器和指令。 我特别关心的是控制器和服务的比较。但是,没有一个帖子告诉我什么是控制器可以执行服务不能执行的操作,反之亦然。 可以列出它吗?或者仅仅是在angular的用法上规范? 问题答案: 控制器 通常用于绑定视图。控制器管理视图的生命周期,应将其视为视图控制器。将为视图的每个实例创建一个新的控制器,这意味着,如