Unverified Commit 3c9ba0a3 authored by Han Gao's avatar Han Gao Committed by GitHub
Browse files

api server exception management and code optimization (#397) (#2397)



* api server exception management and code optimization (#397)

* add unit test for exception handler.

* fix some style and naming issues

Co-authored-by: default avatardailidong <dailidong66@gmail.com>
parent 320469df
Loading
Loading
Loading
Loading
+58 −71
Original line number Diff line number Diff line
@@ -18,6 +18,7 @@ package org.apache.dolphinscheduler.api.controller;


import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.exceptions.ApiException;
import org.apache.dolphinscheduler.api.service.AccessTokenService;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
@@ -37,6 +38,7 @@ import springfox.documentation.annotations.ApiIgnore;
import java.util.Map;

import static org.apache.dolphinscheduler.api.enums.Status.*;

/**
 * access token controller
 */
@@ -54,6 +56,7 @@ public class AccessTokenController extends BaseController{

    /**
     * create token
     *
     * @param loginUser  login user
     * @param userId     token for user id
     * @param expireTime expire time for the token
@@ -63,6 +66,7 @@ public class AccessTokenController extends BaseController{
    @ApiIgnore
    @PostMapping(value = "/create")
    @ResponseStatus(HttpStatus.CREATED)
    @ApiException(CREATE_ACCESS_TOKEN_ERROR)
    public Result createToken(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                              @RequestParam(value = "userId") int userId,
                              @RequestParam(value = "expireTime") String expireTime,
@@ -70,17 +74,13 @@ public class AccessTokenController extends BaseController{
        logger.info("login user {}, create token , userId : {} , token expire time : {} , token : {}", loginUser.getUserName(),
                userId, expireTime, token);

        try {
        Map<String, Object> result = accessTokenService.createToken(userId, expireTime, token);
        return returnDataList(result);
        }catch (Exception e){
            logger.error(CREATE_ACCESS_TOKEN_ERROR.getMsg(),e);
            return error(CREATE_ACCESS_TOKEN_ERROR.getCode(), CREATE_ACCESS_TOKEN_ERROR.getMsg());
        }
    }

    /**
     * generate token string
     *
     * @param loginUser  login user
     * @param userId     token for user
     * @param expireTime expire time
@@ -89,17 +89,13 @@ public class AccessTokenController extends BaseController{
    @ApiIgnore
    @PostMapping(value = "/generate")
    @ResponseStatus(HttpStatus.CREATED)
    @ApiException(GENERATE_TOKEN_ERROR)
    public Result generateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                                @RequestParam(value = "userId") int userId,
                                @RequestParam(value = "expireTime") String expireTime) {
        logger.info("login user {}, generate token , userId : {} , token expire time : {}", loginUser, userId, expireTime);
        try {
        Map<String, Object> result = accessTokenService.generateToken(userId, expireTime);
        return returnDataList(result);
        }catch (Exception e){
            logger.error(GENERATE_TOKEN_ERROR.getMsg(),e);
            return error(GENERATE_TOKEN_ERROR.getCode(), GENERATE_TOKEN_ERROR.getMsg());
        }
    }

    /**
@@ -119,13 +115,14 @@ public class AccessTokenController extends BaseController{
    })
    @GetMapping(value = "/list-paging")
    @ResponseStatus(HttpStatus.OK)
    @ApiException(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR)
    public Result queryAccessTokenList(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                                       @RequestParam("pageNo") Integer pageNo,
                                       @RequestParam(value = "searchVal", required = false) String searchVal,
                                       @RequestParam("pageSize") Integer pageSize) {
        logger.info("login user {}, list access token paging, pageNo: {}, searchVal: {}, pageSize: {}",
                loginUser.getUserName(), pageNo, searchVal, pageSize);
        try{

        Map<String, Object> result = checkPageParams(pageNo, pageSize);
        if (result.get(Constants.STATUS) != Status.SUCCESS) {
            return returnDataListPaging(result);
@@ -133,14 +130,11 @@ public class AccessTokenController extends BaseController{
        searchVal = ParameterUtils.handleEscapes(searchVal);
        result = accessTokenService.queryAccessTokenList(loginUser, searchVal, pageNo, pageSize);
        return returnDataListPaging(result);
        }catch (Exception e){
            logger.error(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getMsg(),e);
            return error(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getCode(),QUERY_ACCESSTOKEN_LIST_PAGING_ERROR.getMsg());
        }
    }

    /**
     * delete access token by id
     *
     * @param loginUser login user
     * @param id        token id
     * @return delete result code
@@ -148,21 +142,18 @@ public class AccessTokenController extends BaseController{
    @ApiIgnore
    @PostMapping(value = "/delete")
    @ResponseStatus(HttpStatus.OK)
    @ApiException(DELETE_ACCESS_TOKEN_ERROR)
    public Result delAccessTokenById(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                                     @RequestParam(value = "id") int id) {
        logger.info("login user {}, delete access token, id: {},", loginUser.getUserName(), id);
        try {
        Map<String, Object> result = accessTokenService.delAccessTokenById(loginUser, id);
        return returnDataList(result);
        }catch (Exception e){
            logger.error(DELETE_ACCESS_TOKEN_ERROR.getMsg(),e);
            return error(Status.DELETE_ACCESS_TOKEN_ERROR.getCode(), Status.DELETE_ACCESS_TOKEN_ERROR.getMsg());
        }
    }


    /**
     * update token
     *
     * @param loginUser  login user
     * @param id         token id
     * @param userId     token for user
@@ -173,6 +164,7 @@ public class AccessTokenController extends BaseController{
    @ApiIgnore
    @PostMapping(value = "/update")
    @ResponseStatus(HttpStatus.OK)
    @ApiException(UPDATE_ACCESS_TOKEN_ERROR)
    public Result updateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                              @RequestParam(value = "id") int id,
                              @RequestParam(value = "userId") int userId,
@@ -181,13 +173,8 @@ public class AccessTokenController extends BaseController{
        logger.info("login user {}, update token , userId : {} , token expire time : {} , token : {}", loginUser.getUserName(),
                userId, expireTime, token);

        try {
        Map<String, Object> result = accessTokenService.updateToken(id, userId, expireTime, token);
        return returnDataList(result);
        }catch (Exception e){
            logger.error(UPDATE_ACCESS_TOKEN_ERROR.getMsg(),e);
            return error(UPDATE_ACCESS_TOKEN_ERROR.getCode(), UPDATE_ACCESS_TOKEN_ERROR.getMsg());
        }
    }

}
+2 −0
Original line number Diff line number Diff line
@@ -27,6 +27,8 @@ public enum Status {

    SUCCESS(0, "success", "成功"),

    INTERNAL_SERVER_ERROR_ARGS(10000, "Internal Server Error: {0}", "服务端异常: {0}"),

    REQUEST_PARAMS_NOT_VALID_ERROR(10001, "request parameter {0} is not valid", "请求参数[{0}]无效"),
    TASK_TIMEOUT_PARAMS_ERROR(10002, "task timeout parameter is not valid", "任务超时参数无效"),
    USER_NAME_EXIST(10003, "user name already exists", "用户名已存在"),
+34 −0
Original line number Diff line number Diff line
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dolphinscheduler.api.exceptions;

import org.apache.dolphinscheduler.api.enums.Status;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * controller exception annotation
 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface ApiException {
    Status value();
}
+48 −0
Original line number Diff line number Diff line
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dolphinscheduler.api.exceptions;

import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

/**
 * Exception Handler
 */
@ControllerAdvice
@ResponseBody
public class ApiExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e, HandlerMethod hm) {
        logger.error(e.getMessage(), e);
        ApiException ce = hm.getMethodAnnotation(ApiException.class);
        if (ce == null) {
            return Result.errorWithArgs(Status.INTERNAL_SERVER_ERROR_ARGS, e.getMessage());
        }
        Status st = ce.value();
        return Result.error(st);
    }

}
+3 −0
Original line number Diff line number Diff line
@@ -83,6 +83,9 @@ public class AccessTokenService extends BaseService {
    public Map<String, Object> createToken(int userId, String expireTime, String token) {
        Map<String, Object> result = new HashMap<>(5);

        if (userId <= 0) {
            throw new IllegalArgumentException("User id should not less than or equals to 0.");
        }
        AccessToken accessToken = new AccessToken();
        accessToken.setUserId(userId);
        accessToken.setExpireTime(DateUtils.stringToDate(expireTime));
Loading