@RestControllerAdvice 不工作.我使用的是 Spring Boot 2.2.6 版本 [英] @RestControllerAdvice is not working .I am using Spring boot 2.2.6 version

查看:14
本文介绍了@RestControllerAdvice 不工作.我使用的是 Spring Boot 2.2.6 版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过全局异常处理程序处理我的控制器中的空指针异常,但没有返回预期的响应.我在此处包含了所有类:

I am trying to handle Null Pointer exception in my controller through global exception handler but is not returning the expected response.I have enclosed all the classes here :

以下代码供参考:控制器:

below code for reference: Controller:

    package com.apps.developerblog.app.ws.ui.controller;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;

    import javax.validation.Valid;

    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import com.apps.developerblog.app.ws.ui.model.request.UpdateUserRequestModel;
    import com.apps.developerblog.app.ws.ui.model.request.UserDetailsRequestModel;
    import com.apps.developerblog.app.ws.ui.model.response.UserRest;
    import com.apps.developerblog.ws.exception.UserServiceException;

    @RestController
    @RequestMapping("/users") // http://localhost
    public class UserController {
        Map<String, UserRest> users;

        @GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<UserRest> getUser(@PathVariable("userId") String userId) {

            if (true)
                throw new UserServiceException("A user serviec exception is thrown");
            if (users.containsKey(userId)) {
                return new ResponseEntity<UserRest>(users.get(userId), HttpStatus.OK);
            } else {
                return new ResponseEntity<UserRest>(HttpStatus.NO_CONTENT);
            }

        }

        /*
         * @GetMapping public String getUsers(@RequestParam(value = "page", defaultValue
         * = "2") int page,
         * 
         * @RequestParam(value = "limit") int limit,
         * 
         * @RequestParam(value = "sort", defaultValue = "desc", required = false) String
         * sort) { return "get User was called with page=" + page + " limit =" + limit +
         * " and sort=" + sort; }
         */

        @PostMapping(consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = {
                MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<UserRest> createUser(@Valid @RequestBody UserDetailsRequestModel userDetails) {
            String userId = UUID.randomUUID().toString();
            UserRest returnValue = new UserRest();
            returnValue.setEmail(userDetails.getEmail());
            returnValue.setFirstName(userDetails.getFirstName());
            returnValue.setLastName(userDetails.getLastName());
            returnValue.setUserId(userId);

            if (users == null)
                users = new HashMap<>();
            users.put(userId, returnValue);

            return new ResponseEntity<UserRest>(returnValue, HttpStatus.OK);

        }

        @PutMapping(path = "/{userId}", consumes = { MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
                        MediaType.APPLICATION_JSON_VALUE })
        public UserRest updateUser(@PathVariable String userId,
                @Valid @RequestBody UpdateUserRequestModel userDetailsRequestModel) {
            UserRest storedUserDetails = users.get(userId);
            storedUserDetails.setFirstName(userDetailsRequestModel.getFirstName());
            storedUserDetails.setLastName(userDetailsRequestModel.getLastName());
            users.put(userId, storedUserDetails);
            return storedUserDetails;
        }

        @DeleteMapping(path = "/{userId}")
        public ResponseEntity<String> deleteUser(@PathVariable String userId) {
            if (users.containsKey(userId)) {
                users.remove(userId);
                return new ResponseEntity<String>("User Deleted ", HttpStatus.OK);
            } else {
                return new ResponseEntity<String>("User Not  Deleted ", HttpStatus.NOT_FOUND);
            }

        }

    }

GlobalExceptional:
package com.apps.developerblog.ws.exception;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 *
 * @author 
 */
@RestControllerAdvice
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiErrorResponse constraintViolationException(ConstraintViolationException ex, WebRequest request) {
        return new ApiErrorResponse(500, 5001, ex.getMessage());
    }

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiErrorResponse noHandlerFoundException(Exception ex, WebRequest reques) {
        return new ApiErrorResponse(404, 4041, ex.getMessage());
    }

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }

    @ExceptionHandler(value = { NullPointerException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse nullPointerException(NullPointerException ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }

    @ExceptionHandler(value = { UserServiceException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse UserServiceException(UserServiceException ex, WebRequest reques) {
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }
}

package com.apps.developerblog.ws.exception;

/**
 * @author
 */
public class ApiErrorResponse {

    private int status;
    private int code;
    private String message;

    public ApiErrorResponse(int status, int code, String message) {
        this.status = status;
        this.code = code;
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "ApiErrorResponse{" + "status=" + status + ", code=" + code + ", message=" + message + '}';
    }
}


Error class:

package com.apps.developerblog.ws.exception;

public class UserServiceException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public UserServiceException(String message) {
        super(message);

    }

}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mobile-app-ws</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mobile-app-ws</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml/jackson-xml-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>




    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

推荐答案

请尝试在您的上下文中添加以下代码,您的问题非常抽象且不完整.

Please try adding following code in your context, your question is very abstract and incomplete.

@ControllerAdvice
class StatusControllerAdvice {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> notFoundException(final RuntimeException e) {
//        return new ResponseEntity<String>("false", HttpStatus.INTERNAL_SERVER_ERROR);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

@RestController
@RequestMapping("/status")
public class StatusController {

    @GetMapping("/string")
    public String getString() {
        return "OK";
    }

    @GetMapping(value = "/file")
    public String getImage() {
        File file = new File("/home/ashish1");
        if (file.exists()) {
            return "true";
        }
        throw new RuntimeException("Invalid File");
    }
}

如何访问这个网址:

http://localhost:8080/status/file

这篇关于@RestControllerAdvice 不工作.我使用的是 Spring Boot 2.2.6 版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆