当前位置:网站首页>Live classroom system 05 background management system
Live classroom system 05 background management system
2022-07-25 14:40:00 【z754916067】
Catalog
- pom.xml
- Configuration files and startup classes
- Service modular
- mapper
- Configuration class
- Instructor management module
- To configure Swagger2
- Define the unified return result object
- United return json data
- Condition paging query instructor list interface
- Add instructor interface
- Modify the instructor interface
- Delete lecturer interface in batch
- Unified exception handling
- Specific exception handling
- Handle custom exceptions
pom.xml
First supplement service Of 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ggkt_parent</artifactId>
<groupId>com.class</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.class</groupId>
<artifactId>service</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>service_vod</module>
<!-- <module>service_order</module>-->
<!-- <module>service_activity</module>-->
<!-- <module>service_user</module>-->
<!-- <module>service_wechat</module>-->
<!-- <module>service_live</module>-->
</modules>
<dependencies>
<!-- <dependency>-->
<!-- <groupId>com.class</groupId>-->
<!-- <artifactId>service_utils</artifactId>-->
<!-- <version>0.0.1-SNAPSHOT</version>-->
<!-- </dependency>-->
<!-- Data carriers -->
<dependency>
<groupId>com.class</groupId>
<artifactId>model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--web Need to start project -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Service registration -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- The service call feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- flow control -->
<!-- <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>-->
<!-- Developer tools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes> <include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
as well as service_vod Of pom.xml, It must be reconstructed at that time … The project structure is too messy
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>service</artifactId>
<groupId>com.class</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.class</groupId>
<artifactId>service_vod</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.54</version>
</dependency>
<!-- The date toolbar depends on -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>vod_api</artifactId>
<version>2.1.4</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
Configuration files and startup classes
The configuration file
stay service_vod/src/main/resource Created in application.properties, According to their own environment
# Service port
server.port=8301
# service name
spring.application.name=service-vod
# Environment settings :dev、test、prod
spring.profiles.active=dev
# mysql Database connection
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/glkt_vod?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# return json The global time format of
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#mybatis journal
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
Start class
stay service_vod/src/java/vod Create ServiceVodApplication As a startup class
package vod;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServiceVodApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceVodApplication.class, args);
}
}
Service modular
establish service Folder , Establish the lecturer's service, Pay attention to Interface
package vod.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import model.vod.Teacher;
public interface TeacherMapper extends BaseMapper<Teacher> {
}
impl
service Generally, it is an interface , You also need an implementation class , namely impl To separate the calling class from its concrete implementation .
It needs to be impl on @Service mark , because @Service Its function is to turn spring In container bean instantiate , But only implementation classes can be used new Instantiated , So for each service Need to implement classes .
Why inject service Interface rather than its implementation impl, Because you need to follow Controller–Service Interface –ServiceImpl Implementation class –Mapper Interface mode , Interfaces are needed between modules .
package vod.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import model.vod.Teacher;
import org.springframework.stereotype.Service;
import vod.mapper.TeacherMapper;
import vod.service.TeacherService;
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper,Teacher> implements TeacherService {
}
mapper
establish mapper, And dao It's the same thing , That is, encapsulate some sql operation .
establish TeacherMapper.java
package vod.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface TeacherMapper extends BaseMapper {
}
xml
establish TeacherMapping.xml, There is nothing written in it , Because the functions needed at present have been encapsulated , If there is customization at that time SQL Query rewrite .
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.ggkt.vod.mapper.TeacherMapper">
</mapper>
Configuration class
establish config Folder , establish VodConfig, take mapper Join in spring Containers ,@MapperScan In its java Search under folder , so vod.mapper that will do .
package vod.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
@Configuration
// Its scanning range is in its own java Under the folder so vod.mapper that will do
@MapperScan("vod.mapper")
public class VodConfig {
}
Instructor management module
demand
When adding courses , You need to select the lecturer , So we should manage lecturers , So write instructor based CRUD operation .
The code generator used in the video , I'd better write it by myself …
First create controller Of module, Then create TeacherController, Remember to be in controller Injected inside service
use @RestController Declare as a controller and @Controller The difference is that the latter cannot return a page .
@GetMapping take HTTP Get Mapping to In a particular way .
function : Query all instructors
// Query the list of all instructors
@GetMapping("findAll")
public List<Teacher> findAll(){
List<Teacher> list = teacherService.list();
return list;
}
Running results , visit :http://localhost:8301/admin/vod/teacher/findAll, There is already json data 
problem :nacos
When running, it always shows nacos It didn't start successfully
java.lang.IllegalStateException: failed to req API:/nacos/v1/ns/instance after all servers([localhost:8848]) tried: failed to req API:localhost:8848/nacos/v1/ns/instance. code:500 msg: java.net.ConnectException: Connection refused: connect
hold service Inside pom.xml Comment out
<!-- Service registration -->
<!-- <dependency>-->
<!-- <groupId>com.alibaba.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>-->
<!-- </dependency>-->
<!-- The service call feign -->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-openfeign</artifactId>-->
<!-- </dependency>-->
function : Delete instructor interface logically
@DeleteMapping Used for processing HTTP DELETE request , And map the request to the delete method .
@PathVariable Match the above {id}, Can be used to map URL Place a place holder in the target method's parameters
// Delete Instructor
//@DeleteMapping Used for processing HTTP DELETE request , And map the request to the delete method
@DeleteMapping("removd/{id}")
//@PathVariable Match the above {id}, Can be used to map URL Place a place holder in the target method's parameters
public boolean removeById(@PathVariable String id){
return teacherService.removeById(id);
}
test
Because deleting the instructor interface is delete submission , The test cannot be accessed directly by using the browser , It can be tested by tools , such as Postman, Here through integration Swagger2 Conduct interface test
controller Code aggregation
package vod.controller;
import model.vod.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vod.service.TeacherService;
import java.util.List;
@RestController
@RequestMapping(value = "admin/vod/teacher")
public class TeacherController {
// Inject sevice
@Autowired
private TeacherService teacherService;
// Query the list of all instructors
@GetMapping("findAll")
public List<Teacher> findAll(){
List<Teacher> list = teacherService.list();
return list;
}
// Delete Instructor
//@DeleteMapping Used for processing HTTP DELETE request , And map the request to the delete method
@DeleteMapping("removd/{id}")
//@PathVariable Match the above {id}, Can be used to map URL Place a place holder in the target method's parameters
public boolean removeById(@PathVariable String id){
return teacherService.removeById(id);
}
}
To configure Swagger2
ggkt_parent Next create the sub module common
common Modules introduce dependencies
stay common Inside pom.xml We introduce dependency into the system , The final code is
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ggkt_parent</artifactId>
<groupId>com.class</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common</artifactId>
<packaging>pom</packaging>
<modules>
<module>service_utils</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided </scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided </scope>
</dependency>
<!--lombok To simplify entity classes : Need to install lombok plug-in unit -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</project>
establish swagger2 Configuration class
Delete the inside src Folder , Create sub module folder service_utils, Its pom.xml by
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>common</artifactId>
<groupId>com.class</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.class</groupId>
<artifactId>service_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
<packaging>jar</packaging>
</project>
Delete src Folder , In its main/java Created in swagger Folder , To create a Swagger2Config.java Configuration class , Pay attention to the , If the annotation cannot be found , So pom.xml Inside parent Of artifactId There is a problem , It needs to be declared as common.
@Bean
@Bean It's a method level annotation , Mainly used in @Configuration In the annotated class , It can also be used in @Component In the annotated class .
introduce service_utils rely on
stay service Introduced into the module service_utils rely on , In its pom.xml Add in
<dependency>
<groupId>com.class</groupId>
<artifactId>service_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
Start the class to add comments
Add... To the startup class @ComponentScan(“swagger”), Let it scan the following @component, Note that the statements are package Name , instead of groupId Or other … Stuck for a long time
@SpringBootApplication
@ComponentScan("swagger")
public class ServiceVodApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceVodApplication.class, args);
}
}
Define interface description and parameter description
go back to TeacherController in , Definition swagger2 Interface description and parameter description , Declare above it @Api(tags = “ Instructor management interface ”)
Declaration enabled swagge [email protected]
And in the corresponding method @ApiOperation(“ function ”)
The code is
@Api(tags = " Instructor management interface ")
@RestController
@RequestMapping(value = "admin/vod/teacher")
@EnableSwagger2
public class TeacherController {
// Inject sevice
@Autowired
private TeacherService teacherService;
// Query the list of all instructors
@ApiOperation(" List of all instructors ")
@GetMapping("findAll")
public List<Teacher> findAll(){
List<Teacher> list = teacherService.list();
return list;
}
// Delete Instructor
//@DeleteMapping Used for processing HTTP DELETE request , And map the request to the delete method
@ApiOperation(" Logical deletion ")
@DeleteMapping("removd/{id}")
//@PathVariable Match the above {id}, Can be used to map URL Place a place holder in the target method's parameters
public boolean removeById(@PathVariable String id){
return teacherService.removeById(id);
}
}
start-up swagger2 Interface
Now run the program , Get into http://localhost:8301/swagger-ui.html, At this time, I stepped on a big pit , You need to set controller Also scan in !!!!, Because they are put in the same bag in the course , And I don't have , For more than an hour …
@ComponentScan(basePackages = "vod")

Try the interface

It can be seen that 200
Check in the database 
I can't find it at this time .
Define the unified return result object
The project needs results in json returns , Therefore, it is necessary to unify the data format of the interface .
At this time, define the basic data format
Returns a list of
{
"code": 200,
"message": " success ",
"data": [
{
"id": 2,
"name": " Mr. Ouyang ",
"intro": " Senior lecturer "
}
],
"ok": true
}
Back to pagination
{
"code": 200,
"message": " success ",
"data": {
"records": [
{
"id": 2,
"name": " Mr. Ouyang ",
"intro": " Senior lecturer "
},
{
"id": 4,
"name": " Shangguan teacher ",
"intro": " Senior lecturer "
},
{
"id": 5,
"name": " Oriental teacher ",
"intro": " Senior teacher "
}
],
"total": 10,
"size": 3,
"current": 1,
"orders": [],
"hitCount": false,
"searchCount": true,
"pages": 2
},
"ok": true
}
No data returned
{
"code": 200,
"message": " success ",
"data": null,
"ok": true
}
Failure
{
"code": 201,
"message": " Failure ",
"data": null,
"ok": false
}
United return json data
Create results enum
stay service_utils Module creation Result Folder , use enum Define the return status code
@Getter
public enum ResultCodeEnum {
SUCCESS(200," success "),
FAIL(201, " Failure "),
SERVICE_ERROR(2012, " Service exception "),
DATA_ERROR(204, " Data exception "),
ILLEGAL_REQUEST(205, " Illegal request "),
REPEAT_SUBMIT(206, " Repeated submission "),
LOGIN_AUTH(208, " Not logged in "),
PERMISSION(209, " No authority "),
PHONE_CODE_ERROR(211, " Mobile phone verification code error "),
MTCLOUD_ERROR(210, " The live broadcast interface is abnormal "),
COUPON_GET(220, " The coupon has been received "),
COUPON_LIMIT_GET(221, " Coupons have been issued "),
FILE_UPLOAD_ERROR( 21004, " File upload error "),
FILE_DELETE_ERROR( 21005, " File deletion error "),
VOD_PALY_ERROR(209, " Please watch after purchase "),;
private Integer code;
private String message;
private ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
Create a result class
Notice the use of generics
@Data
@ApiModel(value = " Global unified return results ")
public class Result<T> {
@ApiModelProperty(value = " Return code ")
private Integer code;
@ApiModelProperty(value = " Return message ")
private String message;
@ApiModelProperty(value = " Return the data ")
private T data;
public Result(){
}
public static <T> Result<T> build(T body,Integer code,String message){
// Create a result
Result<T> result = new Result<>();
if(body!=null) result.setData(body);
result.setCode(code);
result.setMessage(message);
return result;
}
// Successful operation
public static <T> Result<T> ok(T data){
return build(data,200," success ");
}
public static <T> Result<T> fail(){
return Result.fail(null);
}
// operation failed Return failed data
public static<T> Result<T> fail(T data){
return build(data, 201," Failure ");
}
public Result<T> message(String msg){
this.setMessage(msg);
return this;
}
public Result<T> code(Integer code){
this.setCode(code);
return this;
}
}
modify controller Return results
// Inject sevice
@Autowired
private TeacherService teacherService;
// Query the list of all instructors
@ApiOperation(" List of all instructors ")
@GetMapping("findAll")
public Result findAll(){
List<Teacher> list = teacherService.list();
return Result.ok(list).message(" Query data successful ");
}
// Delete Instructor
//@DeleteMapping Used for processing HTTP DELETE request , And map the request to the delete method
@ApiOperation(" Logical deletion ")
@DeleteMapping("remove/{id}")
//@PathVariable Match the above {id}, Can be used to map URL Place a place holder in the target method's parameters
public Result removeById(@PathVariable String id){
boolean isSuccess = teacherService.removeById(id);
if(isSuccess){
return Result.ok(null);
}else {
return Result.fail(null);
}
}
At this point, you can see the return 
Condition paging query instructor list interface
Query the lecturer list in pages .
Create configuration class
stay VodConfig Add paging plug-ins , Manage containers as pager objects .
@Configuration
// Attention from package The package starts scanning
@MapperScan("vod.mapper")
public class VodConfig {
// Paging plug-ins
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
Create a query condition object
Its position in the model/vo/vod Medium TeacherQueryVo, Mainly for the inquiry of lecturers , But the content of the query is not as extensive as that stored in the database .
Its content
@Data
public class TeacherQueryVo {
@ApiModelProperty(value = " Name of lecturer ")
private String name;
@ApiModelProperty(value = " title 1 Senior lecturer 2 Chief lecturer ")
private Integer level;
@ApiModelProperty(value = " Arrival time ")
private String joinDateBegin;
@ApiModelProperty(value = " Arrival time ")
private String joinDateEnd;
}
To write controller
@ApiParam Represents adding metadata to parameters , That is, declare what parameters are required
@PathVariable Used to receive the above limit and page
// Paging query
@ApiOperation(value = " Get paging list ")
@PostMapping("{page}/{limit}")
public Result index(
@ApiParam(name = "page", value = " The current page number ", required = true)
@PathVariable Long page,
@ApiParam(name = "limit", value = " Records per page ", required = true)
@PathVariable Long limit,
@ApiParam(name = "teacherVo", value = " Query object ", required = false)
@RequestBody(required = false) TeacherQueryVo teacherQueryVo){
// establish page object , According to the specified delivery of the current page and the number of records per page
Page<Teacher> pageParam = new Page<>(page,limit);
// Get the condition value of the instructor
// name
String name = teacherQueryVo.getName();
// Level
Integer level = teacherQueryVo.getLevel();
// Starting time
String joinDateBegin = teacherQueryVo.getJoinDateBegin();
// End time
String joinDateEnd = teacherQueryVo.getJoinDateEnd();
// Encapsulation condition
QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
if(!StringUtils.isEmpty(name)){
wrapper.like("name",name);
}
if(!StringUtils.isEmpty(level)) {
wrapper.eq("level",level);
}
if(!StringUtils.isEmpty(joinDateBegin)) {
wrapper.ge("join_date",joinDateBegin);
}
if(!StringUtils.isEmpty(joinDateEnd)) {
wrapper.le("join_date",joinDateEnd);
}
// Get paging results
Page<Teacher> page1 = teacherService.page(pageParam, wrapper);
return Result.ok(page1);
}
Add instructor interface
What's coming in is Teacher Type of requestbody,, call service It comes with save Just deposit .
@ApiOperation(value = " Add instructor interface ")
@PostMapping("save")
public Result save(@RequestBody Teacher teacher){
teacherService.save(teacher);
return Result.ok(null);
}
Modify the instructor interface
according to id Query lecturer
@ApiOperation(value = " according to id Get the instructor ")
@GetMapping("get/{id}")
public Result get(@PathVariable Long id){
Teacher byId = teacherService.getById(id);
return Result.ok(byId);
}
Modify the instructor's method
@PostMapping and @PutMapping Equal effect , Are used to submit information to the server . If it's adding information , Tend to use @PostMapping, If it's an update , Tend to use @PutMapping.
@ApiOperation(value = " Modify Instructor ")
@PutMapping("update")
public Result updateById(@RequestBody Teacher teacher){
teacherService.updateById(teacher);
return Result.ok(null);
}
Delete lecturer interface in batch
@ApiOperation(value = " according to id List delete ")
@DeleteMapping("batchRemove")
public Result batchRemove(@RequestBody List<Long> idList){
teacherService.removeByIds(idList);
return Result.ok(null);
}
Unified exception handling
The system needs exceptions to be used as a unified return result object , And the abnormal information of the system needs to be handled uniformly .
Create a unified exception handler
stay servic_utils Created in execption Folder , establish GlobalExceptionHandler.java Processing class .
@ControllerAdvice The essence is a Component, It is mainly used to process global data , You can handle global exceptions .
@ResponseBody The role of java Object to json Formatted data .
The error type captured by the following method is the largest Exception
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail().message(" Performed global exception handling ")
}
}
Specific exception handling
Add exception handling methods
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.fail().message(" Processing of specific exceptions is performed ");
}
Handle custom exceptions
First, customize an exception , Also in Exception Under the folder
@NoArgsConstructor Generate parameterless constructor
@AllArgsConstructor Generate full parameter constructors
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GgktException extends RuntimeException{
private Integer code;
private String msg;
}
Throw custom exception
try{
int a=1/0;
}catch(Exception e){
throw new GgktException(2001," Custom exception occurred ");
}
Add custom exception handling method
@ExceptionHandler(GgktException.class)
@ResponseBody
public Result error(GgktException e){
e.printStackTrace();
return Result.fail().message(e.getMsg()).code(e.getCode());
}
边栏推荐
- kibana操作es
- 应用实践:Paddle分类模型大集成者[PaddleHub、Finetune、prompt]
- Go language founder leaves Google
- 河源市区推出消防安全主题奶茶 助推夏季火灾防控
- Can the variable name be in Chinese? Directly fooled people
- Idea error failed to determine a suitable driver class
- 基于浏览器的分屏阅读
- SQL优化的一些建议,希望可以帮到和我一样被SQL折磨的你
- OverTheWire-Natas
- Famous handwritten note taking software recruit CTO · coordinate Shenzhen
猜你喜欢

I2C设备驱动程序的层次结构

河源市区推出消防安全主题奶茶 助推夏季火灾防控

Go language founder leaves Google

Idea settings ignore file configuration when submitting SVN

Resource not found: rgbd_launch 解决方案

元器件采购系统的主要功能,数字化采购助力元器件企业飞速发展
![[MySQL series] - how much do you know about the index](/img/d7/5045a846580be106e2bf16d7b30581.png)
[MySQL series] - how much do you know about the index

The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%

Resource not found: rgbd_ Launch solution

为什么中建、中铁都需要这本证书?究竟是什么原因?
随机推荐
Flask SSTI injection learning
H5页面input输入框弹起数字键盘,需要支持小数点
牛客多校 E G J L
SQL优化的一些建议,希望可以帮到和我一样被SQL折磨的你
Quickly set up dobbo demo
Introduction to PHP
QObject源码剖析-d指针和q指针
C language and SQL Server database technology
Educational Codeforces Round 132 (Rated for Div. 2) C,D+AC自动机
English语法_不定代词 - other / another
thymeleaf通过样式控制display是否显示
物理量与单位符号的书写标准
The security market has entered a trillion era, and the security B2B online mall platform has been accurately connected to deepen the enterprise development path
Keys and scan based on redis delete keys with TTL -1
I2C设备驱动程序的层次结构
Number of high-quality number pairs [bit operation characteristics + abstract ability evaluation + grouping fast statistics]
PHP website design ideas
Doris learning notes integration with other systems
直播课堂系统05-后台管理系统
Matplotlib data visualization three minutes entry, half an hour enchanted?